import 'dart:async';
import 'dart:convert';
import 'dart:ui';

// import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/UI/Loading.dart';
import 'package:magic_car/baoxiu/brandselect.dart';
import 'package:magic_car/baoxiu/cartype.dart';
import 'package:magic_car/baoxiu/insurance.dart';
import 'package:magic_car/bussiness/bussinessEditResult.dart';
import 'package:magic_car/jiance/inspectresults.dart';
import 'package:magic_car/jiance/pre_test_report.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/colors.dart';
import 'package:magic_car/util/galleryphotoview.dart';
import 'package:magic_car/zhanshi/cheyuandetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
import 'dart:io';
// import 'package:date_format/date_format.dart';
import 'package:magic_car/UI/mykeyboard.dart' as board;
import 'package:flutter_blue/flutter_blue.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_cupertino_date_picker_fork/flutter_cupertino_date_picker_fork.dart';
import 'package:date_format/date_format.dart';
import 'package:magic_car/UI/bottom_Menu_page.dart';
import 'package:magic_car/UI/userbottom_Menu_page.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'dart:io';
import 'package:dio/dio.dart';
import 'dart:typed_data';
import 'package:package_info/package_info.dart';
import 'package:http/http.dart' as http;
import 'package:flutter/services.dart';
import 'package:flutter/src/services/hardware_keyboard.dart' as prefix;
// import 'package:flutter/src/se';
//检测页面重写121
class AssementPapularinspects extends StatefulWidget {
  //final Map param;
  final String oid;
  final int type;
  final Map picParam;
  AssementPapularinspects(this.oid, this.type, this.picParam);

  @override
  _MyHomePageState createState() =>
      new _MyHomePageState(this.oid, this.type, this.picParam);
}

class _MyHomePageState extends State<AssementPapularinspects>
    with WidgetsBindingObserver {
  GlobalKey _globalKey;
  List<Offset> _points = <Offset>[];
  List formList;
  int role;
  //final Map param;
  final String oid;
  final int type;
  final Map picParam;

  bool showkb = false;
  _MyHomePageState(this.oid, this.type, this.picParam);
  bool select = false;
  String itemid;
  bool resize = false; //是否收起按钮
  Map _cityNames;

  int qimoyi_type = 0; //漆膜仪类型


  String MIN_DATETIME = '2010-05-01';
  String MAX_DATETIME = '2030-11-01';
  String INIT_DATETIME = '2020-05-01';

  DateTimePickerLocale _locale = DateTimePickerLocale.zh_cn;
//DateTimePickerLocale _locale = Locale('zn');
  List<DateTimePickerLocale> _locales = DateTimePickerLocale.values;

  String _format = 'yyyy-MMMM-dd';
  TextEditingController _formatCtrl = TextEditingController();

  DateTime _dateTime;

  Map param;
  List testItem;

  Map picinspect = new Map();
  bool loaddata = false;
  String status;
  Map formalities;
  Map oldformalities;

  Map cartbrand = new Map();
  Map cartype = new Map();

  Map orderInfo;
  // FlutterBlue flutterBlue = FlutterBlue.instance;
  // BluetoothDevice device;
  bool showUrl = false;

  String pwdData = '输入车牌';

  Color Select_Color;

  int line_Height1 = 1;
  Color line_color1 = Colors.red;

  int line_Height2 = 1;
  Color line_color2 = Colors.red;

  int line_Height3 = 1;
  Color line_color3 = Colors.red;

  String Checkresult = '';
  bool connectBluetooth = false;
  bool scantarget = false; //是否扫描到目标设备
  bool savebtn = false;
  FlutterBlue flutterBlue = FlutterBlue.instance;
  BluetoothDevice device;
  Map currentTest = new Map();
  int selectIndex;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  ScrollController scrollController = new ScrollController();
  TextEditingController buchongControll = new TextEditingController();
  TextEditingController resultController = new TextEditingController();
  TextEditingController resultPriceController = new TextEditingController();
  TextEditingController chejiaController = new TextEditingController();
  TextEditingController pailiangController = new TextEditingController();
  TextEditingController fadongjiController =
      new TextEditingController(); //发动机控制器
  TextEditingController biaoxianController =
      new TextEditingController(); //表显里程控制器
  TextEditingController jiaoqiangController =
      new TextEditingController(); //交强险控制器
  TextEditingController shangyeController =
      new TextEditingController(); //商业保险控制器
  TextEditingController guohuController = new TextEditingController(); //过户此时控制器
  TextEditingController weituoController = new TextEditingController(); //委托人信息
  TextEditingController xinyongdaimaController = new TextEditingController();
  // VoidCallback：没有参数并且不返回数据的回调
  VoidCallback _showBottomSheetCallback;

  bool isfirstScan = false;

  int seconds = 720;

  bool canceltimes = false;

  Timer _countdownTimer; //自动保存的计时器
  //final PageRouteBuilder _homeRoute;

  String current_brand; //当前品牌
  String current_type; //当前车型号

  String current_brandName = "选择品牌";
  String current_cartypeName = "选择车型";
  FocusNode _focusNode = FocusNode(); //蛋疼的写法
  FocusNode _focusNode1 = FocusNode(); //蛋疼的写法
  FocusNode _focusNode2 = FocusNode(); //蛋疼的写法
  FocusNode _focusNode3 = FocusNode(); //蛋疼的写法
  FocusNode _focusNode4 = FocusNode(); //蛋疼的写法
  FocusNode _focusNode5 = FocusNode(); //蛋疼的写法
  FocusNode _focusNode6 = FocusNode(); //蛋疼的写法

  List showdefalut = ['车辆信息', '结构件', '浸泡检测', '失火检测', '照片上传'];

  String xsz_url = "";

  AppBar appBar = AppBar(
    title: new Text('检测'),
    backgroundColor: Colors.white,
    iconTheme: new IconThemeData(color: Colors.black),
    elevation: 0,
    // backgroundColor: Color.fromRGBO(255, 204, 48, 1),
  );
  initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 注册监听器
    _globalKey = GlobalKey();
    _showBottomSheetCallback = _showBottomSheet;

    //输入框焦点
    // _focusNode.addListener(() {
    //   if (!_focusNode.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });
    // _focusNode1.addListener(() {
    //   if (!_focusNode1.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });
    // _focusNode2.addListener(() {
    //   if (!_focusNode2.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });
    // _focusNode3.addListener(() {
    //   if (!_focusNode3.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });
    // _focusNode4.addListener(() {
    //   if (!_focusNode4.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });
    // _focusNode5.addListener(() {
    //   if (!_focusNode5.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });
    // _focusNode6.addListener(() {
    //   if (!_focusNode6.hasFocus) {
    //     print('失去焦点');
    //     saveResult();
    //   } else {
    //     print('得到焦点');
    //   }
    // });

    formList = [
      {
        "title": '购车发票/过户票',
        'sub_title': '云A00001',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "value": "",
        "code": "invoice",
        "mustimg": 1,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '购置税证',
        'sub_title': '云A00001',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "Tax",
        "value": "",
        "mustimg": 1,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '行驶证',
        'sub_title': '云A00001',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "vehicle",
        "value": "",
        "mustimg": 1,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '年检有效期',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "100",
        "code": "yearcheck_e_time",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '登记证',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "registration",
        "value": "",
        "mustimg": 1,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '过户次数',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "transfer",
        "value": "",
        "mustimg": 1,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0,
        'controller': guohuController
      },
      {
        "title": '交强险有效期',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "100",
        "code": "compu_e_time",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '交强险保险公司',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "4",
        "code": "compu_name",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '交强险保单号',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "vehicles_e_time",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0,
        'controller': jiaoqiangController
      },
      // {
      //   "title": '车船税有效期',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': "1",
      //   "code": "vehicles_e_time",
      //   "value": "请选择日期",
      //   "mustimg":1
      // },
      // {
      //   "title": '车船险随车出售',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': "3",
      //   "code": "vehicles",
      //   "value": "是"
      // },
      {
        "title": '商业险保单号',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "business_price",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0, 'controller': shangyeController
      },
      // {
      //   "title": '商业险金额',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': "2",
      //   "code": "business_price",
      //   "value": ""
      // },
      {
        "title": '商业险保险公司',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "4",
        "code": "business_name",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
      {
        "title": '特殊车辆',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "4",
        "code": "specialcar",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
    ];
    _cityNames = {
      '北京': ['东城区', '西城区'],
      '郑州': ['高新区', '金水区'],
      '上海': ['黄浦区', '徐汇区'],
      '杭州': ['西湖区', '滨江区'],
    };
    formalities = {
      "invoice": '', //购车发票/过户票
      "Tax": '', //购置税证
      "vehicle": '', //行驶证
      //"vehicles_b_time": '', //年检有效期开始时间
      "yearcheck_e_time": '', //年检有效期结束时间
      "registration": '', //登记证
      "transfer": '', //过户次数
      //"compu_b_time": '', //交强险有效期 begin
      "compu_e_time": '', //交强险有效期 end
      "compu_name": '', //交强险保险公司
      // "vehicles_b_time": '', //车船税有��期 start
      "vehicles_e_time": '', //车船税���效期 end
      //"business_b_time": '', // 商业保��有效期 start
      //"business_e_time": '', //商业保险有效期  end
      // "business_sell_by_car": false, //商业险随车出售
      "business_price": '', //商业险金额
      // "business_name": '', //商业保险公司
      // "nameplate": '', //车身铭牌
      // "busines": '', //是否有商业险
      // "compu": '', //是否有交强险
      // "vehicles": '', //车船税是否
      // "compu_name1": '',
      "business_name": '',
      "specialcar": '',
      "images": []
    };
    cartbrand = {'value': '选择品牌', 'brand_id': ''};
    cartype = {'value': '选择车系', 'type_id': ''};
    loaddetail();
    //starttimes();
    //showAlert();
  }

// 不要忘记在这里释放掉Timer
  @override
  void dispose() {
    super.dispose();
    // setState(() {
    //   canceltimes = true;
    // });
    // _countdownTimer?.cancel();
    // _countdownTimer = null;

    WidgetsBinding.instance.removeObserver(this); // 移除监听器
  }

  //启动定时器
  starttimes() {
    const period = const Duration(seconds: 5);

    _countdownTimer = Timer.periodic(period, (timer) {
      seconds--;
      if (seconds == 0) {
        _countdownTimer.cancel(); //一小时后结束时间计时
      }

      //到时回调
      if (!canceltimes) saveResult();
    });
  }

   List imageModelinspectitem(data) {
    List img_temp = [
      "https://car3.autoimg.cn/cardfs/product/g1/M09/3F/A8/240x180_0_q95_c42_autohomecar__ChwFqV69W4KAf_AzAAShphUBgV4514.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M09/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W32Ad5ehAAT2abQFAio994.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M08/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W3uATe71AASA9ZdptWg816.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M0B/73/06/240x180_0_q95_c42_autohomecar__ChsEmF69W3qAYeneAAQeve0abAo167.jpg",
    ];
    List imgList = List();
    for (int x = 0; x < data.length; x++) {
      
      GalleryExampleItem item = GalleryExampleItem();
      item.id = '$x';
      item.resource = data[x][1];
      // item.resource = data[x]["url"];
      imgList.add(item);
    }
    print(imgList.first.id);

    return imgList;
  }

//重写蓝牙模块
  scan() async {
    flutterBlue.scan().listen((scanResult) async {
      // do something with scan result
      device = scanResult.device;

      if (device.name.startsWith('LS')) {
        Toast.show('漆膜仪连接成功', context);
        setState(() {
          connectBluetooth = true;
        });
        print('找到指定设备。');

        await device.connect();
        device = device;
        flutterBlue.stopScan();
        List<BluetoothService> services = await device.discoverServices();
        services.forEach((service) async {
          // do something with service
          var characteristics = service.characteristics;
          for (BluetoothCharacteristic c in characteristics) {
            // List<int> value = await c.read();
            // print(value);
            await c.setNotifyValue(true);
            c.value.listen((value) {
              Toast.show('值发生改变', context);

              //print(value.length);
              if (value.length > 0) {
                //第一位先转换为16进制
                print(value[8].toRadixString(16).toUpperCase());
                var hexStr = "";
                if (value[9] == 255) {
                  //负数
                } else {
                  if (value[8] < 10) {
                    hexStr = '0' +
                        value[11].toString() +
                        '0' +
                        value[10].toString() +
                        '0' +
                        value[9].toString() +
                        '0' +
                        value[8].toString();
                  } else {
                    var str = value[8].toRadixString(16).toUpperCase();
                    if (str.length == 1) {
                      str = "0" + str;
                    }
                    var str1 = value[9].toRadixString(16).toUpperCase();
                    if (str1.length == 1) {
                      str1 = "0" + str1;
                    }
                    print('第九位16进制转换：' + str1);
                    hexStr = '0' +
                        value[11].toString() +
                        '0' +
                        value[10].toString() +
                        '0' +
                        str1 +
                        str;
                  }

                  print(hexStr);
                  print('转换结果' + _hexToInt(hexStr).toString());
                  Toast.show(_hexToInt(hexStr).toString(), context);
                  if (currentTest.containsKey('numerical_value')) {
                    //有这个检测结果数组，从里面添加
                    // if(currentTest)
                    List tempArr = currentTest['numerical_value'];
                    if (tempArr.length == int.parse(currentTest['testnum'])) {
                      //达到数量之后开始校验数组

                      Toast.show('此项测量数量达上线，请进行下一项检测', context);
                      tempArr.sort();
                      double re = tempArr.last;
                      List tempList = currentTest['item'].split(',');
                      if (re <= 180) {
                        currentTest["value"] = tempList[0];
                      } else if (re <= 330) {
                        currentTest["value"] = tempList[1];
                      } else if (re > 330) {
                        currentTest["value"] = tempList[2];
                      }
                      setState(() {
                        currentTest = currentTest;
                      });
                      print(tempArr.last);
                      return;
                    }
                    double re = _hexToInt(hexStr) / 10;
                    // if(re>100){
                    //   print('需要社区小数点');
                    //   tempArr.add(int.parse(re.toString()));
                    // }else
                    tempArr.add(_hexToInt(hexStr) / 10);
                  } else {
                    currentTest['numerical_value'] = [];
                    currentTest['numerical_value'].add(_hexToInt(hexStr) / 10);
                  }
                  print(currentTest);
                  setState(() {
                    currentTest = currentTest;
                  });
                }
              }
              // do something with new value
            });
          }
        });
        //flutterBlue.stopScan();
      }
      print('${device.name} found! rssi: ${scanResult.rssi}');
    });

    /// 关闭扫描���作，避免内存泄漏
  }

//漆膜仪连接
  connect() async {
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();

    if (isfirstScan == false) {
      setState(() {
        isfirstScan = true;
      });
      flutterBlue.scan().listen((scanresult) {
        print('蓝牙名称' + scanresult.device.name);
        String deveceName = scanresult.device.name;
        if (deveceName.startsWith('Guoou') || deveceName.startsWith('LS')) {
          //flutterBlue.stopScan();
          flutterBlue.stopScan();
          if (scantarget == false) {
            showAlerts(deveceName);
          }
          //2020/11/27 增加漆膜仪类型
          if (deveceName.startsWith('Guoou')) {
            qimoyi_type = 1;
          } else if (deveceName.startsWith('LS')) {
            qimoyi_type = 0;
          }
          setState(() {
            scantarget = true;
          });

          device = scanresult.device;
        } else {
          //Toast.show('正在重新扫描设备', context);
        }
      });
    }

    //}
  }

  handelScanresult() {}

  showAlerts(texts) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('找到设备' + texts + '是否连接？',
                              style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            // Navigator.pop(context);
                            startconnetc();
                          },
                          child: Center(
                              child: Text('连接',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
    // showDialog<Null>(
    //   context: this.context,
    //   builder: (BuildContext context) {
    //     return new AlertDialog(
    //         title: Text('找到设备,是否连接？'),
    //         content: new Text(texts),
    //         actions: <Widget>[
    //           new FlatButton(
    //               onPressed: () {
    //                 Navigator.of(context, rootNavigator: true).pop();
    //                 // Navigator.pop(context);
    //               },
    //               child:
    //                   new Text('否', style: new TextStyle(color: Colors.red))),
    //           new FlatButton(
    //               onPressed: () async {
    //                 // await Navigator.pop(context);
    //                 // Navigator.pop(_);
    //                 // Navigator.of(context, rootNavigator: true).pop();
    //                 startconnetc();
    //                 // Navigator.pop(context);
    //               },
    //               child: new Text(
    //                 '是',
    //                 style: new TextStyle(color: Colors.black),
    //               ))
    //         ]);
    //   },
    // );
  }

  //测试数据转换
  String changeValue(value) {
    String str = value.toRadixString(16).toUpperCase().toString().length>1?
    value.toRadixString(16).toUpperCase().toString():"0"+(value.toRadixString(16).toUpperCase().toString());
    return str;
  
  }

  

  startconnetc() async {
    Navigator.pop(context);

    await device.connect();
    Toast.show('漆膜仪连接成功', context);
    setState(() {
      connectBluetooth = true;
    });

    List<BluetoothService> services = await device.discoverServices();
    services.forEach((service) async {
      // do something with service
      var characteristics = service.characteristics;
      for (BluetoothCharacteristic c in characteristics) {
        // List<int> value = await c.read();
        // print(value);
        // Toast.show('扫描设备属性......'+ c.uuid.toString(), context,duration:2);
        print('uuid--' + c.uuid.toString());
        if (c.uuid.toString() == "0000ffe1-0000-1000-8000-00805f9b34fb") {
           //Toast.show('定位设备读写属性......', context);
          // if (c.uuid.toString() == "0000ffe1-0000-1000-8000-00805f9b34fb") {
          await c.setNotifyValue(true);
          c.value.listen((value) async {
           
            // postuuid(value.toString());
            print('byte 数组$value');
            var hexStr = "";
            if (qimoyi_type == 1) {
               //Toast.show("接收原始数值打印：$value", context,duration:5);

              if (value.length > 2 && value[0] == 0 && value[1] == 0) {
                int lengths = value.length;
                if (lengths > 5) {
                  var nums = changeValue(value[lengths - 2])+
                  changeValue(value[lengths - 3])
                  +changeValue(value[lengths - 4])
                  +changeValue(value[lengths - 5]);

                 

                  Map<String, String> params = {"data": nums};
                  http.Response res = await http.post(
                     Uri.parse( HttpHelper.baseUrl + HttpHelper.API_Post_UUID),
                      body: params);
                  final result = json.decode(res.body.toString());
                  if (result["info"] > 0) {
                    hexStr = result["info"].toString();
                  }
                 

                  print('数据装换结果$hexStr');
                } else {
                  
                }
               
              }else{
                String recieve = Utf8Codec().decode(value).toString().trim();
                  // String recieve = Utf8Codec().decode([0, 0, 80, 0, 19, 0, 95, 6, 117, 114, 220, 13, 44, 60, 120, 63, 195, 66, 70]).toString().trim();
                  print('recieve=' + recieve);

                  if (recieve != null && recieve.length > 0) {
                    //Toast.show("接收数值打印：$recieve", context,duration:5);
                    List temp_num = recieve.split(":");
                    if (temp_num.length > 0) {
                      List temp_num1 = temp_num[1].split("^");
                      if (temp_num1.length > 0) {
                        print("字符长度" + (temp_num1[0].length - 2).toString());
                        hexStr =
                            temp_num1[0].substring(0, temp_num1[0].length - 1);
                      }
                    }
                    //hexStr = recieve;
                  }
              }
            } else if (qimoyi_type == 0) {
              print('值发生改���$value');
              if (value.length > 0) {
                //第一位先转换为16进制
                //  print(value[8].toRadixString(16).toUpperCase());

                if (value[9] == 255) {
                  //负数
                } else {
                  if (value[8] < 10) {
                    hexStr = '0' +
                        value[11].toString() +
                        '0' +
                        value[10].toString() +
                        '0' +
                        value[9].toString() +
                        '0' +
                        value[8].toString();
                  } else {
                    var str = value[8].toRadixString(16).toUpperCase();
                    if (str.length == 1) {
                      str = "0" + str;
                    }
                    var str1;
                    if (value[9] < 10) {
                      str1 = '0' + value[9].toString();
                    } else {
                      str1 = value[9].toRadixString(16).toUpperCase();
                      if (str1.length == 1) {
                        str1 = "0" + str1;
                      }
                    }
                    print('第九位数值转换:' + str1);
                    hexStr = '0' +
                        value[11].toString() +
                        '0' +
                        value[10].toString() +
                        '0' +
                        str1 +
                        str;
                  }

                  print('16进制转换:$hexStr');

                  print('转换结果' + _hexToInt(hexStr).toString());
                  // Toast.show(_hexToInt(hexStr).toString(), context);

                }
              }
            }
            if (hexStr == "") return; //没有测量值

            if (currentTest.containsKey('numerical_value')) {
              //有这个检测结果数组，从里面添加
              // if(currentTest)
              List tempArr = currentTest['numerical_value'];
              print('此项需要检测个数：' + currentTest['testnum']);
              if (tempArr.length > int.parse(currentTest['testnum']) ||
                  tempArr.length == int.parse(currentTest['testnum'])) {
                //达到数量之后开���校验数组

                Toast.show('此项测量数量已达上限，请进行下一项检测', context);
                tempArr.sort();
                double re = tempArr.last;
                List tempList = currentTest['item'].split(',');
                if (re <= 180) {
                  currentTest["value"] = tempList[0];
                } else if (re <= 330) {
                  currentTest["value"] = tempList[1];
                } else if (re > 330) {
                  currentTest["value"] = tempList[2];
                }
                setState(() {
                  currentTest = currentTest;
                });

                // return;
              } else {
                if (qimoyi_type == 0) {
                  double re = _hexToInt(hexStr) / 10;
                  tempArr.add(_hexToInt(hexStr) / 10);
                } else if (qimoyi_type == 1) {
                  tempArr.add(double.parse(hexStr));
                }
                
              }
            } else {
              currentTest['numerical_value'] = [];
              // if (_hexToInt(hexStr) / 10 < 1000) {
              if (qimoyi_type == 0) {
                currentTest['numerical_value'].add(_hexToInt(hexStr) / 10);
              } else if (qimoyi_type == 1) {
                currentTest['numerical_value'].add(double.parse(hexStr));
              }
              // }
            }

            setState(() {
              currentTest = currentTest;
            });
            // do something with new value
          });
        }
      }
    });
  }

  showAlert() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('是否连接漆膜仪检测?使用前，请确保手机蓝牙已打开！',
                              style: TextStyle(fontSize: 14)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            connect();
                          },
                          child: Center(
                              child: Text('连接',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
    // showDialog(
    //   context: context,
    //   builder: (BuildContext context) {
    //     return new AlertDialog(
    //         title: Text('提示!'),
    //         content: new Text('是否连接漆膜仪检测?'),
    //         actions: <Widget>[
    //           new FlatButton(
    //               onPressed: () {
    //                 Navigator.of(context, rootNavigator: true).pop();
    //               },
    //               child:
    //                   new Text('否', style: new TextStyle(color: Colors.red))),
    //           new FlatButton(
    //               onPressed: () {
    //                 Navigator.of(context, rootNavigator: true).pop();
    //                 connect();
    //                 // scan();

    //                 // Navigator.pop(context);
    //               },
    //               child: new Text(
    //                 '是',
    //                 style: new TextStyle(color: Colors.black),
    //               ))
    //         ]);
    //   },
    // );
  }

  //上传行驶证
  //选择图片
  getxszimgs(type, index) async {
    var image;
    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    }
    if (image == null) return;
    // LoadingPage loadpage = new LoadingPage(context);
    // loadpage.show();
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();
    Map imgitem;

    HttpHelper.upLoadImageNocompress(_files, (data) {
      //loadpage.close();
      print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        scanxsz(data["url"]);
        //  setState(() {
        //   xsz_url = data["url"];
        // });
      }
    }, params: map);
  }

  //识别行驶证
  scanxsz(url) {
    Toast.show('信息识别中...', context);
    Map<String, String> param = new Map();

    param['img'] = url;
    HttpHelper.post(HttpHelper.API_Scanxsz, (data) async {
      //loadpage.close();
      //loadpage.close();
      if (data != null) {
        
        print(data);
        Map response1 = data['Response'];
        List tempdata =[];
         if (orderInfo["inspectorItemsResult"] != false) {
           tempdata = orderInfo["inspectorItemsResult"]["otherData"]
              ["checkData"];
         }else{
           tempdata = testItem;
         }
        if (response1.containsKey('FrontInfo')) {
          for (var v in tempdata){
            v['temp_mustimg'] = '0';
            for (var k in v["post"]) {
            

              if (k["id"] == "3029") {
                if (this.type == 1) {
                  if (response1['FrontInfo'].containsKey('PlateNo')) {
                    setState(() {
                      pwdData = response1['FrontInfo']['PlateNo'];
                      k["value"] = k["value"] == "" ? pwdData : k["value"];
                    });
                    
                  }
                  //车牌处理
                  // k["value"] = k["value"] == "" ? pwdData : k["value"];
                  // setState(() {
                  //   pwdData = k["value"];
                  // });
                } else {
                  k["value"] = orderInfo["car_num"];
                }
              } else if (k["id"] == "3035") {
                // k["value"] = orderInfo["brand_string"]['name'] +
                //     '/' +
                //     orderInfo["cartype_string"]['name'];
              } else if (k["id"] == "3030") {
                //车架号的处理
                if (response1['FrontInfo'].containsKey('Vin')) {
                  chejiaController.text = response1['FrontInfo']['Vin'];

                  setState(() {
                    k["value"] = response1['FrontInfo']['Vin'];
                    // chejia.text = response1['FrontInfo']['Vin'];
                  });
                }
                // chejiaController.text = k["value"];
              } else if (k['id'] == "4032") {
                //发动机号处理
                 if (response1['FrontInfo'].containsKey('EngineNo')) {
                  fadongjiController.text = response1['FrontInfo']['EngineNo'];

                  setState(() {
                    k["value"] = response1['FrontInfo']['EngineNo'];
                    // chejia.text = response1['FrontInfo']['Vin'];
                  });
                }
               // fadongjiController.text = k["value"];
              } else if (k['id'] == "4030") {
              //  biaoxianController.text = k["value"];
              } else if (k['id'] == "4031") {
               // pailiangController.text = k["value"];
              }
            }
          }


       

         
        } else {
          Toast.show("没有识别到相关信息", context);
        }
        setState(() {
          xsz_url = url;
        });
      }
    }, params: param);
  }

  //行驶证上传
  Widget xingshiimg() {
    Widget content = Padding(
        padding: new EdgeInsets.fromLTRB(0, 0, 0, 1),
        child: Container(
          color: Colors.white,
          width: double.infinity,
          // height: 160,
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Padding(
                padding: new EdgeInsets.fromLTRB(20, 10, 10, 0),
                child: RichText(
                  text: TextSpan(
                      text: "行驶证识别",
                      style: TextStyle(
                          fontSize: 15,
                          color: Color.fromRGBO(102, 102, 102, 1)),
                      children: [
                        // TextSpan(
                        //     text: '*',
                        //     style: TextStyle(fontSize: 14, color: Colors.red))
                      ]),
                ),
              ),
              Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      color: Colors.white,
                      // height: 100,
                      child: new Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            InkWell(
                                onTap: () {
                                  //选择图片
                                  showDialog(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return new SimpleDialog(
                                          title: new Text('选择'),
                                          children: <Widget>[
                                            new SimpleDialogOption(
                                              child: new Text('相机'),
                                              onPressed: () {
                                                Navigator.pop(context);
                                                getxszimgs(0, 1);
                                              },
                                            ),
                                            new SimpleDialogOption(
                                              child: new Text('相册'),
                                              onPressed: () {
                                                Navigator.pop(context);
                                                getxszimgs(1, 1);
                                              },
                                            )
                                          ],
                                        );
                                      });
                                },
                                child: Center(
                                  child: xsz_url == ""
                                      ? Image.asset(
                                          'resource/images/user/xsz.png',
                                          width: 150,
                                          height: 150,
                                          fit: BoxFit.fitHeight)
                                      : CachedNetworkImage(
                                          imageUrl: xsz_url,
                                          width: MediaQuery.of(context)
                                                  .size
                                                  .width -
                                              30,
                                          // height: 150,
                                          fit: BoxFit.fitWidth),
                                ))
                            // new Container(child: buildCImgs(item["title"]=="车源封面图片"?thumb:imgs))
                          ]))),

              //  Expanded(
              //   child:
            ],
          ),
        ));
    return content;
  }

  loaddetail() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String roles = pref.getString('role');

    setState(() {
      role = int.parse(roles);
    });

    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    String api = HttpHelper.API_OrderDetail;
    if (this.type == 2) {
      api = HttpHelper.API_BussinessOrderDetail;
    }

    HttpHelper.post(api, (data) async {
      Future.delayed(Duration(seconds: 2), () {
        // connect();
        //showAlert(); 提示框先不弹出
      });
      if (data != null) {
        print(data);
        // return;
        if (data["code"].toString() == "1") {
          setState(() {
            status = data["info"]["status"].toString();
            orderInfo = data["info"];
            current_brand = data["info"]["brand_id"];
            current_type = data["info"]["cartype_id"];
          });
          // if (data["info"]["status"] != "0" && data["info"]["status"] != "1") {
          // if (data["info"]["status"] != "0" && data["info"]["status"] != "1") {
          if (data["info"]["inspectorItemsResult"] != false) {
            // List<String> order = [];
            // if (pref.getStringList('orders') != null) {
            //   order = pref.getStringList('orders');
            // }
            // if (order.length > 0) {
            //   for (var i = 0; i < order.length; i++) {
            //     Map result = jsonDecode(order[i]);
            //     if (result['order_id'] == this.oid) {
            //       //
            //       data["info"]["inspectorItemsResult"] = result;
            //     }
            //   }
            // }

            //当有检测结果时
            //修改状态
            for (var v in data["info"]["inspectorItemsResult"]["otherData"]
                ["checkData"]) {
              v['temp_mustimg'] = '0';
              for (var k in v["post"]) {
                if (k['id'] == "6592") {
                  //委托人信息
                  weituoController.text = k["value"];
                }
                if (k['id'] == "6593") {
                  xinyongdaimaController.text = k['value'];
                }
                if (k["id"] == "3029") {
                  k["value"] = k["value"] == ""
                      ? orderInfo['car_num']
                      : k["value"]; //从车辆信息里面同步车牌数据
                  setState(() {
                    pwdData = k["value"];
                  });
                  // if (this.type == 1) {
                  //   //车牌处理
                  //   // k["value"] = k["value"] == "" ? pwdData : k["value"];
                  //   k["value"] = k["value"] == "" ?orderInfo['car_num']  : k["value"];//从车辆信息里面同步车牌数据
                  //   setState(() {
                  //     pwdData = k["value"];
                  //   });
                  // } else {
                  //   k["value"] = orderInfo["car_num"];
                  // }
                } else if (k["id"] == "3035") {
                  if (orderInfo['brand_id'] != "0" &&
                      orderInfo['cartype_id'] != "0") {
                    k["value"] = orderInfo["brand_string"]['name'] +
                        '/' +
                        orderInfo["cartype_string"]['name'];
                    current_brandName = orderInfo["brand_string"]['name'];
                    current_cartypeName = orderInfo["cartype_string"]['name'];
                  } else {
                    k["value"] = current_brandName + '/' + current_cartypeName;
                  }
                } else if (k["id"] == "3030") {
                  //车架号的处理
                  chejiaController.text = k["value"];
                } else if (k['id'] == "4032") {
                  //发动机号处理
                  fadongjiController.text = k["value"];
                } else if (k['id'] == "4030") {
                  //表显里程
                  biaoxianController.text =
                      k["value"] == "" ? orderInfo['bxlc'] : k["value"];
                } else if (k['id'] == "4031") {
                  //排量
                  pailiangController.text =
                      k["value"] == "" ? orderInfo['pl'] : k["value"];
                } else if (k['id'] == "4033") {
                  //排放标准
                  // pailiangController.text = k["value"]==""?orderInfo['pfbz']:k["value"];
                }
              }

              if (v['id'] == '4000') {
                //照片和检测项分开

                if (role == 1) {
                  List tempImg = v['post'];
                  bool hasrenche = false;
                  tempImg.forEach((element) {
                    if (element['name'] == "人车合照") {
                      hasrenche = true;
                    }
                  });
                  if (picParam.length > 0 && !hasrenche)
                    v['post'].add(picParam);
                  // if (picParam.length > 0 && v['post'].length == 12)
                  //   v['post'].add(picParam);
                } //增加人车合照暂时不增加

              }
            }
            setState(() {
              testItem = data["info"]["inspectorItemsResult"]["otherData"]
                  ["checkData"];
              oldformalities =
                  data["info"]["inspectorItemsResult"]["formalities"];
              loaddata = true;
              status = data["info"]["status"].toString();
              Checkresult = data["info"]["inspectorItemsResult"]['result'];
              resultController.text =
                  data["info"]["inspectorItemsResult"]['result'];
              resultPriceController.text =
                  data["info"]["inspectorItemsResult"]['result_price'];
            });

            Map foemlitile =
                data["info"]["inspectorItemsResult"]["formalities"];

            var templist = formList;

            List tempList = foemlitile['images'];

            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];
              //处理图片情况
              if (tempList.length > 0) {
                for (var j = 0; j < tempList.length; j++) {
                  var itemss = tempList[j];
                  if (itemss['code'] == code) {
                    formList[i]['urlArr1'] = itemss['urlArr1'];
                    formList[i]['hasimg'] = 1;
                  }
                }
              }

              templist[i]["value"] = foemlitile[code];
              if (code == "vehicles") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
              if (code == "business_sell_by_car") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
              if (code == "yearcheck_e_time") {
                //年检有效期为空的情况
                if (templist[i]["value"] == "") {
                  // formList[i]["value"] = "请选择日期";
                }
              }
              if (code == "compu_e_time") {
                //交强险有效期为空的情况
                if (templist[i]["value"] == "") {
                  // formList[i]["value"] = "请选择日期";
                }
              }

              if (code == "compu_name") {
                //交强保险公司为空的情况
                // if (templist[i]["value"] == "") {
                //   formList[i]["value"] = "请选择保险公司";
                // }
              }

              if (code == "vehicles_e_time") {
                //车船税为空的情况
                if (templist[i]["value"] == "") {
                  // formList[i]["value"] = "交强险保单号";
                } else {
                  jiaoqiangController.text = templist[i]["value"];
                }
              }

              if (code == "business_name") {
                //商业保险公司为空的情况
                if (templist[i]["value"] == "") {
                  // formList[i]["value"] = "商业保险公司";
                } else {
                  // shangyeController.text = templist[i]["value"];
                }
              }
              if (code == "business_price") {
                //商业保险公司为空的情况
                if (templist[i]["value"] == "") {
                  //formList[i]["value"] = "商业保险公司";
                } else {
                  shangyeController.text = templist[i]["value"];
                }
              }
              if (code == "specialcar") {
                if (templist[i]["value"] == "") {
                  // formList[i]["value"] = "请选择特殊车辆类型";
                }
              }
              if (code == "transfer") {
                // templist[i]["value"] = orderInfo['ghcs'];
                guohuController.text = templist[i]["value"] == ""
                    ? orderInfo['ghcs']
                    : templist[i]["value"];
              }
            }
            setState(() {
              formList = templist;
              formalities = foemlitile;
            });
          } else {
            loadTestItem(data["info"]["test_type"]);
            var templist = formList;
            var listvalue = this.formalities;
            print(this.formalities);
            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];

              // this.formalities[code]=formList[i]["value"];
              formList[i]["value"] = this.formalities[code] == ""
                  ? formList[i]["value"]
                  : this.formalities[code];
            }

            setState(() {
              formList = formList;
            });
          }

          setState(() {
            //formList = oldlist;
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  //加载检测项
  loadTestItem(type) {
    var types = 1;
    if (type == "事故检测")
      types = 2;
    else if (type == "保修检测")
      types = 3;
    else if (type == "金融检测") types = 4;
    Map<String, String> map = new Map();
    map["type"] = types.toString();
    // if (this.type == 2)
    map['isbussiness'] = '1';
    HttpHelper.post(HttpHelper.API_LoadTestItem, (data) async {
      print(data);

      if (data != null) {
        for (var v in data) {
          if (showdefalut.contains(v['name'])) {

            v['show_report'] = "1";
            v['show_report_s'] = "0";
          } else {
            v['show_report'] = "0";
            v['show_report_s'] = "0";
          }
          v['temp_mustimg'] = '0';
          for (var k in v["post"]) {
            if (showdefalut.contains(v['name'])) {
            } else {
              k['show_report'] = "0";
            }

            //   if (k["id"] == "3029") {
            //     if (this.type == 1) {
            //       //车牌处理
            //       k["value"] = pwdData;
            //       // if(orderInfo['carmsg'].containsKey('plate_number')){
            //       // k["value"]=orderInfo['carmsg']["plate_number"];
            //       // }

            //     } else {
            //       k["value"] = orderInfo["car_num"];
            //       setState(() {
            //         pwdData = orderInfo["car_num"];
            //       });
            //     }
            //   } else if (k["id"] == "3035") {
            //     k["value"] = orderInfo["brand_string"]['name'] +
            //         '/' +
            //         orderInfo["cartype_string"]['name'];
            //   } else if (k['id'] == "4030") {
            //     k["value"] = orderInfo['bxlc'];
            //     biaoxianController.text = orderInfo['bxlc'];
            //   } else if (k['id'] == '4031') {
            //     k["value"] = orderInfo['pl'];
            //     pailiangController.text = orderInfo['pl'];
            //   } else if (k['id'] == '4033') {
            //     k['value'] = orderInfo['pfbz'];
            //   }
          }

          if (v['id'] == '4000') {
            //照片和检测项分开

            if (role == 1) {
              List tempImg = v['post'];
              bool hasrenche = false;
              tempImg.forEach((element) {
                if (element['name'] == "人车合照") {
                  hasrenche = true;
                }
              });
              if (picParam.length > 0 && !hasrenche) v['post'].add(picParam);
              // if (orderInfo["is_start"] == "0") {
              //   v['post'].add(picParam);
              // }
            } //增加人车合照

          }
        }
        setState(() {
          testItem = data;
          loaddata = true;
        });
        saveResult();
      }
    }, params: map);
  }

  checknum() {
    int nums = 0;
    for (var items in testItem) {
      var postdata = items['post'];
      for (var i = 0; i < postdata.length; i++) {
        var item = postdata[i];

        if (item.containsKey('value') && item['mustimg'].toString() != '1') {
          if (item["value"] != "") {
            nums++;
          }
        }
        if (item['post_id'] == '4000') {
          // print('计算已填项目');
          if (item['id'] != '9999') {
            if (item.containsKey('urlArr1')) {
              if (item['urlArr1'].length > 0) {
                nums++;
              }
            }
          } else {
            nums++;
          }
        }

        //图片为比须的情况
        if (item['mustimg'].toString() == '1') {
          if (item.containsKey('urlArr1')) {
            if (item['urlArr1'].length > 0) {
              nums++;
            }
          }
        }
      }
      setState(() {
        items['count'] = nums;
      });
    }

    setState(() {
      testItem = testItem;
    });
  }

  photo(item) async {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child:
                              Text('上传图片?', style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            Navigator.pop(context);
                            //connect();
                            uploadImgs(item, 1);
                          },
                          child: Center(
                              child: Text('相机',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                            uploadImgs(item, 2);
                          },
                          child: Center(
                              child:
                                  Text('相册', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

  
   _saveImg(avatar) async {
    if (Platform.isAndroid) {

      if(await Permission.storage.request().isGranted) {
       var response = await Dio()
            .get(avatar, options: Options(responseType: ResponseType.bytes));
        // final result =
        // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
        final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data));
        print('result:$result');
    }
      // 检查并请求权限
      // PermissionStatus status = await PermissionHandler()
      //     .checkPermissionStatus(PermissionGroup.storage);
      // if (PermissionStatus.granted != status) {
      //   PermissionHandler().requestPermissions(<PermissionGroup>[
      //     PermissionGroup.storage,
      //   ]);
      // } else {
      //   var response = await Dio()
      //       .get(avatar, options: Options(responseType: ResponseType.bytes));
      //   // final result =
      //   // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
      //   final result = await ImageGallerySaver.saveImage(
      //       Uint8List.fromList(response.data));
      //   print('result:$result');
      //   if (result != null) {
      //   } else {}
      // }
    } else {
       if(await Permission.photos.request().isGranted) {
       var response = await Dio()
            .get(avatar, options: Options(responseType: ResponseType.bytes));
        // final result =
        // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
        final result = await ImageGallerySaver.saveImage(
            Uint8List.fromList(response.data));
        print('result:$result');
    }
      // PermissionStatus status = await PermissionHandler()
      //     .checkPermissionStatus(PermissionGroup.photos);
      // if (PermissionStatus.granted != status) {
      //   PermissionHandler().requestPermissions(<PermissionGroup>[
      //     PermissionGroup.photos,
      //   ]);
      // } else {
      //   var response = await Dio()
      //       .get(avatar, options: Options(responseType: ResponseType.bytes));
      //   // final result =
      //   // await ImageGallerySaver.saveFile(Uint8List.fromList(response.data));
      //   final result = await ImageGallerySaver.saveImage(
      //       Uint8List.fromList(response.data));
      //   print('result:$result');
      //   if (result != null) {
      //   } else {}
      // }
    }
    //ImageGallerySaver.saveFile(file)
    // final result = await ImageGallerySaver.saveImage(image);

    // if(Utils.isEmpty(result)){
    //   print('保存失败');
    // }else{
    //   print('保存成功');
    // }
  }
    
   
   
 

  //上传图片
  uploadImgs(item, type) async {
    var image;

    if (type == 1) {
      image = await ImagePicker.pickImage(source: ImageSource.camera);
    } else {
      image = await ImagePicker.pickImage(source: ImageSource.gallery);
    }
    if (image == null) return;
    // File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      // print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        checknum();
        if (item['id'] == '9999') {
          //人车合照单独处理
          print('人车合照上传图片');
          setState(() {
            item['url'] = data['url'];
            item['url2'] = data['filename'];
          });
        } else {
           if (item.containsKey('title') && item['title'] == "行驶证") {
            //同步行驶证图片
            for (var item in testItem) {
              if (item['id'].toString() == "6630") {
                //照片上传项目
                //6639
                for (var picitem in item['post']) {
                  if (picitem['id'].toString() == "6639") {
                    List tempimg1 = picitem.containsKey("urlArr1")
                        ? picitem["urlArr1"]
                        : new List();
                    List tempimg = new List();
                    tempimg.add(data["filename"]);
                    tempimg.add(data["url"]);

                    tempimg1.add(tempimg);
                    setState(() {
                      picitem["urlArr1"] = tempimg1;
                      //hasimg
                      if (picitem.containsKey("hasimg")) {
                        picitem["hasimg"] = 1; //手续信息单独更改内部值
                      }
                    });
                  }
                }
              }
            }
          }
          List tempimg1 =
              item.containsKey("urlArr1") ? item["urlArr1"] : new List();
          List tempimg = new List();
          tempimg.add(data["filename"]);
          tempimg.add(data["url"]);

          tempimg1.add(tempimg);
          setState(() {
            item["urlArr1"] = tempimg1;
            //hasimg
            if (item.containsKey("hasimg")) {
              item["hasimg"] = 1; //手续信息单独更改内部值
            }
          });
          if (type == 1) {
            _saveImg(data["url"]); //相机图片保存到相册
          }
        }
        saveResult();
      }
    }, params: map);
  }

  Widget buildcontent(items) {
    List<Widget> tiles = [];
    Widget content;

    List postdata = items["post"];
    itemid = items["id"];
    // print(param);
    // print('传递数值');
    if (items["mustmodel"].toString() == "1") {
      if (itemid == "3044") {
        print('浸泡检测');
        //浸泡检测单独处理
        tiles.add(Container(
            decoration: new BoxDecoration(
              //color: Colors.white
              color: Color.fromRGBO(238, 238, 238, 1),
            ),
            child: Stack(
              children: <Widget>[
                Align(
                    alignment: Alignment.topCenter,
                    child: Container(
                      color: Colors.white,
                      width: double.infinity,
                      height: items["mustmodel"] == "1" ? 200 : 0,
                      padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
                      child: RepaintBoundary(
                        key: _globalKey,
                        child: Stack(
                          children: [
                            new Image.asset(
                              "resource/images/jiance/qinpao.png",
                              fit: BoxFit.fitHeight,
                            ),
                            Positioned(
                                top: 20,
                                left: 50,
                                right: 30,
                                height: 25,
                                child: new GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (line_Height1 == 3) {
                                        setState(() {
                                          items['position'] = '';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      } else {
                                        setState(() {
                                          items['position'] = 'top';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 3;
                                        });
                                      }
                                    },
                                    child: new Container(
                                        height: 1,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                          width: line_Height1.toDouble(),
                                          color: Colors.red,
                                        )))

                                        //       child:
                                        // new Container(
                                        //   color:Colors.red,
                                        //   height: line_Height1.toDouble()

                                        // )
                                        ))),
                            Positioned(
                                top: 50,
                                left: 50,
                                right: 30,
                                height: 30,
                                child: new GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (line_Height2 == 3) {
                                        setState(() {
                                          items['position'] = '';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      } else {
                                        setState(() {
                                          items['position'] = 'center';
                                          line_Height2 = 3;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      }
                                    },
                                    child: new Container(
                                        height: 1,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                          width: line_Height2.toDouble(),
                                          color: Colors.red,
                                        )))

                                        //       child:
                                        // new Container(
                                        //   color:Colors.red,
                                        //   height: line_Height1.toDouble()

                                        // )
                                        ))),
                            Positioned(
                                top: 80,
                                left: 50,
                                right: 30,
                                height: 30,
                                child: new GestureDetector(
                                    behavior: HitTestBehavior.opaque,
                                    onTap: () {
                                      if (line_Height3 == 3) {
                                        setState(() {
                                          items['position'] = '';
                                          line_Height2 = 1;
                                          line_Height3 = 1;
                                          line_Height1 = 1;
                                        });
                                      } else {
                                        setState(() {
                                          items['position'] = 'bottom';
                                          line_Height2 = 1;
                                          line_Height3 = 3;
                                          line_Height1 = 1;
                                        });
                                      }
                                    },
                                    child: new Container(
                                        height: 1,
                                        decoration: BoxDecoration(
                                            border: Border(
                                                top: BorderSide(
                                          width: line_Height3.toDouble(),
                                          color: Colors.red,
                                        )))

                                        //       child:
                                        // new Container(
                                        //   color:Colors.red,
                                        //   height: line_Height1.toDouble()

                                        // )
                                        )))
                            // GestureDetector(
                            //   onPanUpdate: (DragUpdateDetails details) {
                            //     //按下
                            //     RenderBox referenceBox =
                            //         context.findRenderObject();
                            //     scrollController.animateTo(350.0 + 50,
                            //         duration: new Duration(seconds: 1),
                            //         curve: Curves.ease); //开始划线是列表自动滚动
                            //     // Offset localPosition =  referenceBox.localToGlobal(Offset.zero);
                            //     var localPosition = referenceBox
                            //         .globalToLocal(details.globalPosition);
                            //     // Offset dys = [100.00,100.00];
                            //     // localPosition.dy=100.00;

                            //     //localPosition.y=localPosition.dy-64;
                            //     setState(() {
                            //       _points = new List.from(_points)
                            //         ..add(Offset(
                            //             localPosition.dx,
                            //             localPosition.dy -
                            //                 appBar.preferredSize.height -
                            //                 20));
                            //       // _points = new List.from(_points)
                            //       //   ..add(localPosition);
                            //     });
                            //   },
                            //   onPanEnd: (DragEndDetails details) =>
                            //       _points.add(null), //抬起来
                            // ),
                            // CustomPaint(painter: new SignaturePainter(_points)),
                          ],
                        ),
                      ),
                    )),
              ],
            )
            // Padding(
            //     padding: new EdgeInsets.fromLTRB(0, 15, 0, 0),
            //     child: new ListView(
            //       children: <Widget>[buildcontent()],
            //     )),
            ));
      } else if (itemid == "3077") {
        //灯光模型单独处理
        // tiles.add(Container(
        //     color: Colors.white,
        //     width: double.infinity,
        //     height: 150,
        //     padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
        //     //color: Colors.red,
        //     //color: Colors.red,
        //     child: Align(
        //       alignment: Alignment.topCenter,
        //       child: showLightProblem(itemid, postdata, 1),
        //     )));

        // tiles.add(Container(
        //     color: Colors.white,
        //     width: double.infinity,
        //     height: 150,
        //     padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
        //     //color: Colors.red,
        //     //color: Colors.red,
        //     child: Align(
        //       alignment: Alignment.topCenter,
        //       child: showLightBProblem(itemid, postdata, 2),
        //     )));
      } else {
        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 250,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              // child:new Text('121')
              child: showProblem(itemid, postdata),
            )));
      }
    }

    int counters = 0;

    if(items['id']=="3000"){
      //车辆信息增加行驶证识别
      tiles.add(xingshiimg());
    }

    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      if (item.containsKey('value') && item['mustimg'].toString() != '1') {
        if (item["value"] != "") {
          counters++;
        }
      } else {
        if (item['mustimg'].toString() == '1') {
          if (item.containsKey('urlArr1')) {
            if (item['urlArr1'].length > 0) {
              counters++;
            }
          }
        }

        if (item['post_id'].toString() == '4000') {
          //照片和协议上传处理
          // print('计算已填项目');
          if (item['id'].toString() != '9999') {
            if (item.containsKey('urlArr1')) {
              if (item['urlArr1'].length > 0) {
                counters++;
              }
            }
          } else {
            counters++;
          }
        }
      }
      // if (item.containsKey('value')) {
      //   if (item["value"] != "") {
      //     counters++;
      //   }
      // } else {
      //   if (item['post_id'].toString() == '4000') {
      //     // print('计算已填项目');
      //     if (item['id'].toString() != '9999') {
      //       if (item.containsKey('urlArr1')) {
      //         if (item['urlArr1'].length > 0) {
      //           counters++;
      //         }
      //       }
      //     } else {
      //       counters++;
      //     }
      //   }
      // }
      TextEditingController textEditingController = TextEditingController();
      double height = 80;
      if (item["mustimg"] == "1") height = 270;
      if (items["id"] == "3040") {
        //漆面检测单独
        tiles.add(Padding(
            padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
            child: new GestureDetector(
                onTap: () {
                  // print('点击测量项目');
                  setState(() {
                    currentTest = item;
                    selectIndex = i;
                    // Select_Color=Colors.grey;
                  });
                },
                child: Container(
                  color: selectIndex == i
                      ? Color.fromRGBO(230, 230, 230, 1)
                      : Colors.white,
                  // decoration: new BoxDecoration(
                  // border: new Border(
                  //   //0xffe5e5e5
                  //   //bottom:BorderSide(width: 1)
                  //   )
                  //   ),
                  // height: height,
                  child: new Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      top(item, items),
                      center(item),
                      item.containsKey("numerical_value")
                          ? testresult(item)
                          : new Container(height: 0),
                      item.containsKey("urlArr1")
                          ? imgs(item)
                          : new Container(height: 0)
                    ],
                  ),
                ))));
      } else {
        //print(item['id']);

        if (item['id'] == '9999') {
          //人车合照单独布局
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
              child: Container(
                // color: Colors.white,
                decoration: new BoxDecoration(
                    border: new Border(
                        bottom:
                            BorderSide(width: 1, color: Color(0xffe5e5e5)))),

                // height: height,
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    top(item, items),
                    // center(item),

                    // item.containsKey("numerical_value")? testresult(item):new Text(''),
                    item.containsKey("url")
                        ? rencheImg(item)
                        : new Container(height: 0)
                  ],
                ),
              )));
        } else {
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
              child: Container(
                // color: Colors.white,
                decoration: new BoxDecoration(
                    border: new Border(
                        bottom:
                            BorderSide(width: 1, color: Color(0xffe5e5e5)))),

                // height: height,
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    top(item, items),
                    center(item),
                    //imgs(item)

                    // item.containsKey("numerical_value")? testresult(item):new Text(''),
                    item.containsKey("urlArr1")
                        ? imgs(item)
                        : item.containsKey("url")
                            ? rencheImg(item)
                            : new Container(height: 0)
                  ],
                ),
              )));
        }
      }
    }
    items["count"] = counters.toString();
    if (items['show_report'].toString() == "0") {
      return ExpansionTile(
        trailing: SizedBox(
            width: 22,
            // padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
            child: new Checkbox(
                value: items['show_report_s'] == "0" ? false : true,
                onChanged: (val) {
                  if (val == true) {
                    for (var v in items['post']) {
                      v['show_report'] = "1";
                    }
                  } else {
                    for (var v in items['post']) {
                      v['show_report'] = "0";
                    }
                  }

                  setState(() {
                    items['show_report_s'] = val == true ? "1" : '0';
                  });
                  saveResult();
                })),
        children: tiles,
        onExpansionChanged: (value) {
          FocusScope.of(context).requestFocus(FocusNode());
          if (items['id'] == '3040') {
            //漆面检测，连接漆膜仪提示
            if (value == true) {
              if (connectBluetooth == false) {
                showAlert();
              }
            }
          }
        },

        title: RichText(
            text: TextSpan(
                text: items['name'],
                style: TextStyle(fontSize: 16.0, color: Colors.black,fontWeight:FontWeight.w600),
                children: <TextSpan>[
              TextSpan(
                  text: '*',
                  style: TextStyle(
                      fontSize: 18.0,
                      color:
                          items['ismust'] == "1" ? Colors.red : Colors.white)),
              TextSpan(
                  text: "（" +
                      items['count'] +
                      '/' +
                      postdata.length.toString() +
                      '）',
                  style: TextStyle(fontSize: 12.0, color: Colors.red))
            ])),
        // title: Text(
        //   item["name"],
        //   style: TextStyle(
        //     color: Colors.black,
        //     fontSize: 16,
        //   ),
        // )
      );
    } else {
      return ExpansionTile(
        children: tiles,
        onExpansionChanged: (value) {
          FocusScope.of(context).requestFocus(FocusNode());
          if (items['id'] == '3040') {
            //漆面检测，连接漆膜仪提示
            if (value == true) {
              if (connectBluetooth == false) {
                showAlert();
              }
            }
          }
        },

        title: RichText(
            text: TextSpan(
                text: items['name'],
                style: TextStyle(fontSize: 16.0, color: Colors.black),
                children: <TextSpan>[
              TextSpan(
                  text: '*',
                  style: TextStyle(
                      fontSize: 18.0,
                      color:
                          items['ismust'] == "1" ? Colors.red : Colors.white)),
              TextSpan(
                  text: "（" +
                      items['count'] +
                      '/' +
                      postdata.length.toString() +
                      '）',
                  style: TextStyle(fontSize: 12.0, color: Colors.red))
            ])),
        // title: Text(
        //   item["name"],
        //   style: TextStyle(
        //     color: Colors.black,
        //     fontSize: 16,
        //   ),
        // )
      );
    }
    // content = new Column(
    //     children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
    //     //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
    //     );
    // return content;
  }

//漆膜仪检测的数值
  Widget testresult(item) {
    Widget content;
    List<Widget> tiles = [];
    print(item["testnum"]);
    // int itemnum = int.parse(item["testnum"]);
    int itemnum = item['numerical_value'].length;
    for (var i = 0; i < itemnum; i++) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 5),
          child: new Container(
            height: 30,
            width: 30,

            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
              color: Color(0xFF9E9E9E), // 底色
              //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
              borderRadius:
                  BorderRadius.all(Radius.circular(15.0)), // 也可控件一边圆角大小
            ),

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.center,
                child: new Text(
                  item.containsKey('numerical_value')
                      ? item['numerical_value'][i].toString()
                      : '0',
                  style: TextStyle(color: Colors.white, fontSize: 10),
                )),
          ),
        ),
      );
    }
    tiles.add(
      Padding(
          padding: new EdgeInsets.fromLTRB(10, 3, 0, 5),
          child: new GestureDetector(
            onTap: () {
              setState(() {
                item['numerical_value'] = [];
              });
            },
            child: new Container(
              height: 25,
              width: 40,

              decoration: new BoxDecoration(
                border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
                color: Color(0xFF9E9E9E), // 底色
                //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
                // 也可控件一边圆角大小
              ),

              //color: Colors.red,
              child: new Align(
                  alignment: Alignment.center,
                  child: new Text('清空', style: TextStyle(color: Colors.white))),
            ),
          )),
    );
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    return content;
  }

  //检测项最上面组件
  Widget top(item, items) {
    if (item["post_id"] == "3600") {
      return Padding(
          padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
          child: new Row(
            children: <Widget>[
              RichText(
                  text: TextSpan(
                      text: item["name"],
                      style: TextStyle( fontWeight: FontWeight.w600,
                                              fontSize: 14,
                                              color: Color.fromRGBO(
                                                  102, 102, 102, 1)),
                      children: <TextSpan>[
                    TextSpan(
                        text: '',
                        style: TextStyle(
                            fontSize: 25.0,
                            color: item["ismust"] == "5"
                                ? Colors.red
                                : Colors.white))
                  ])),
              Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
                  child: new GestureDetector(
                      onTap: () {
                        FocusScope.of(context).requestFocus(FocusNode());
                        photo(item);
                      },
                      child: new Image.asset(
                        'resource/images/user/cremra.png',
                        width: 20,
                        height: 20,
                        fit: BoxFit.contain,
                      )))
            ],
          ));
    } else {
      return Padding(
          padding: new EdgeInsets.fromLTRB(15, 5, 0, 0),
          child: new Row(
            children: <Widget>[
              RichText(
                  text: TextSpan(
                      text: item["name"],
                      style: TextStyle( fontWeight: FontWeight.w600,
                                              fontSize: 14,
                                              color: Color.fromRGBO(
                                                  102, 102, 102, 1)),
                      children: <TextSpan>[
                    TextSpan(
                        text: '',
                        style: TextStyle(
                            fontSize: 25.0,
                            color: item["ismust"] == "5"
                                ? Colors.red
                                : Colors.white))
                  ])),
              item["post_id"] != "4000"
                  ? item["mustimg"] == "1" || item["temp_mustimg"] == "1"
                      ? Padding(
                          padding: new EdgeInsets.fromLTRB(10, 2, 0, 0),
                          child: new GestureDetector(
                              onTap: () {
                                FocusScope.of(context)
                                    .requestFocus(FocusNode());
                                photo(item);
                              },
                              child: new Image.asset(
                                'resource/images/user/cremra.png',
                                width: 20,
                                height: 20,
                                fit: BoxFit.contain,
                              )))
                      : new Text('')
                  : Padding(
                      padding: new EdgeInsets.fromLTRB(10, 2, 0, 0),
                      child: new GestureDetector(
                          onTap: () {
                            photo(item);
                          },
                          child: new Image.asset(
                            'resource/images/user/cremra.png',
                            width: 20,
                            height: 20,
                            fit: BoxFit.contain,
                          ))),
              items['show_report_s'] == "1"
                  ? Expanded(
                      child: Align(
                          alignment: Alignment.bottomRight,
                          child: Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 17, 0),
                              child: SizedBox(
                                  width: 22,
                                  // padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                                  child: new Checkbox(
                                      value: item['show_report'] == "0"
                                          ? false
                                          : true,
                                      onChanged: (val) {
                                        setState(() {
                                          item['show_report'] =
                                              val == true ? "1" : '0';
                                        });
                                        saveResult();
                                      })))))
                  : new Container(height: 0)
            ],
          ));
    }
  }

  Widget center(item) {
    if (item["id"] == "3029") {
      //车牌
      return Row(
        children: <Widget>[
          new GestureDetector(
              onTap: () async {
                _showBottomSheetCallback();
              },
              child: Padding(
                  padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
                  child: Text(pwdData))),
          new GestureDetector(
              onTap: () async {
                setState(() {
                  pwdData = "未上牌";
                });
                saveResult();
              },
              child: Padding(
                  padding: new EdgeInsets.fromLTRB(25, 10, 0, 10),
                  child: Text('未上牌？请点击',
                      style: TextStyle(color: Colors.red, fontSize: 14)))),
        ],
      );
    } else if (item["id"] == "3030") {
      //车架号
      return new TextField(
          controller: chejiaController,
          focusNode: _focusNode,
           onChanged: (value) {
                setState(() {
                  item['value'] = value;
                });
                saveResult();
              },
              // textCapitalization: TextCapitalization.characters,
              maxLength: 17,

              // inputFormatters: [
              //   LengthLimitingTextInputFormatter(17), //长度限制17位
              //   WhitelistingTextInputFormatter(RegExp("[A-Z0-9]")), //只允许输入字母
              // ],
              inputFormatters: [
                FilteringTextInputFormatter.allow(RegExp('[0-9A-Z]')),
                FilteringTextInputFormatter.deny(RegExp('[IOQ]')),
              ],
          // onChanged: (value) {
          //   print(value);
          //   if (value.contains('I') ||
          //       value.contains('O') ||
          //       value.contains('Q')) {
          //     chejiaController.text = chejiaController.text
          //         .substring(0, chejiaController.text.length - 2);
          //     print(chejiaController.text);
          //   } else {
          //     setState(() {
          //       item['value'] = value;
          //     });
          //     saveResult();
          //   }
          // },
          // textCapitalization: TextCapitalization.characters,
          // inputFormatters: [
          //   LengthLimitingTextInputFormatter(17), //长度限制17位
          //   WhitelistingTextInputFormatter(RegExp("[A-Z0-9]")), //只允许输入字母
          // ],
          decoration: InputDecoration(
             focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color:item.containsKey('value')? item['value'].length < 17
                          ? Colors.red
                          : Colors.white: Colors.white),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                      color:item.containsKey('value')? item['value'].length < 17
                          ? Colors.red
                          : Colors.white: Colors.white),
                ),
            // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
            hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ));
    } else if (item["id"] == "4030") {
      //表显里程，数字键盘
      return new TextField(
          focusNode: _focusNode1,
          controller: biaoxianController,

          // controller: textEditingController,
          onChanged: (value) {
            print(value);
            setState(() {
              item['value'] = value;
            });
            saveResult();
          },
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
            hintText: item.containsKey("value") ? item['value'] : '请填写里程数精确到个位',
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ));
    } else if (item["id"] == "4032") {
      //发动机号
      return new TextField(
          inputFormatters: [
            LengthLimitingTextInputFormatter(17), //长度限制17位
            WhitelistingTextInputFormatter(RegExp("[A-Z0-9]")), //只允许输入字母
          ],
          // focusNode: _focusNode1,
          controller: fadongjiController,

          // controller: textEditingController,
          onChanged: (value) {
            print(value);
            setState(() {
              item['value'] = value;
            });
            saveResult();
          },
          // keyboardType: TextInputType.number,
          decoration: InputDecoration(
            // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
            hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ));
    } else if (item["id"] == "4031") {
      //排量输入限制处理

      // return new Container(
      //   height: 40,
      //   width: double.infinity,
      //   child:
      //  Row(

      //   children: <Widget>[
      //   new TextField(
      //       controller: pailiangController,
      //       onChanged: (value) {
      //         print(value);
      //         if (RegExp("[a-zA-Z]").hasMatch(value)) {
      //           if (!value.contains('L') || !value.contains('T')) {
      //             pailiangController.text = pailiangController.text
      //                 .substring(0, pailiangController.text.length - 2);
      //             print(pailiangController.text);
      //           } else {
      //             setState(() {
      //               item['value'] = value;
      //             });
      //             saveResult();
      //           }
      //         } else {
      //           saveResult();
      //         }
      //       },
      //       textCapitalization: TextCapitalization.characters,
      //       // inputFormatters: [

      //       //   WhitelistingTextInputFormatter(RegExp("[1-9]")), //只允许输入字母
      //       // ],
      //       decoration: InputDecoration(
      //         hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
      //         border: OutlineInputBorder(
      //           borderSide: BorderSide.none,
      //         ),
      //       )),
      // ]));
      return new TextField(
          controller: pailiangController,
          onChanged: (value) {
            print(value);
            setState(() {
              item['value'] = value;
            });
            saveResult();
            // if(RegExp("[a-zA-Z]").hasMatch(value)){
            // if (!value.contains('L')||!value.contains('T')) {
            //   pailiangController.text = pailiangController.text
            //       .substring(0, pailiangController.text.length - 2);
            //       print(pailiangController.text);
            // } else {
            //   setState(() {
            //     item['value'] = value;
            //   });
            //   saveResult();
            // }
            // }else{
            //    saveResult();
            // }
          },
          textCapitalization: TextCapitalization.characters,
          inputFormatters: [
            WhitelistingTextInputFormatter(RegExp("[0-9.LT]")), //只允许输入字母
          ],
          decoration: InputDecoration(
            hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ));
    } else if (item["id"] == "3035") {
      //选择品牌车系
      return new Row(children: <Widget>[
        new GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: new Padding(
                padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
                child: new Text(current_brandName)),
            onTap: () async {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new BrandSelectRoute(item);
              })).then((param) {
                if (current_brand != param['brand_id']) {
                  // this.formList[2]['value'] = '请选择车型';
                  // this.formList[2]['type_id'] = '';
                  current_type = "";
                  setState(() {
                    orderInfo["cartype_string"]['name'] = "请选择车型";
                  });
                }
                setState(() {
                  current_brand = param['brand_id'];
                  formList = this.formList;
                  //  orderInfo["brand_string"]['name'] = param["value"];
                  current_brandName = param["value"];
                });
                saveResult(); //触发保存
              });
            }),
        new GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: new Padding(
                padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
                child: new Text("/")),
            onTap: () async {}),
        new GestureDetector(
            behavior: HitTestBehavior.opaque,
            child: new Padding(
                padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
                child: new Text(current_cartypeName)),
            onTap: () async {
              Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                return new CartypeSelectRoute(item, current_brand, '0');
              })).then((param) {
                // if (current_brand != param['type_id']) {
                //   this.formList[3]['value'] = '请选���款式';
                //   this.formList[3]['typelist_id'] = '';
                //   //current_type = "";
                // }
                setState(() {
                  current_type = param['type_id'];
                  // orderInfo["cartype_string"]['name'] = param["value"];
                  current_cartypeName = param['value'];
                });
                saveResult(); //触发保存
              });
            })
      ]);
    } else if (item["post_id"] == "3600") {
      //补充图片
      return new Padding(
        padding: new EdgeInsets.fromLTRB(3, 10, 0, 0),
        child: new TextField(
            focusNode: _focusNode2,
            maxLines: 3,
            controller: buchongControll,
            onChanged: (value) {
              print(value);
              setState(() {
                item['value'] = value;
                // buchongControll.text = value;
              });
              saveResult();
            },
            decoration: InputDecoration(
              // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
              hintText: '输入补充内容',
              border: OutlineInputBorder(
                borderSide: BorderSide.none,
              ),
            )),
      );
    } else if (item['id'] == "6592") {
      //委托人信息
      return new TextField(
          controller: weituoController,
          onChanged: (value) {
            print(value);
            setState(() {
              item['value'] = value;
            });
            saveResult();
          },
          textCapitalization: TextCapitalization.characters,
          // inputFormatters: [
          //   WhitelistingTextInputFormatter(RegExp("[0-9.LT]")), //只允许输入字母
          // ],
          decoration: InputDecoration(
            hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ));
    } else if (item['id'] == "6593") {
      //委托人信息
      return new TextField(
          controller: xinyongdaimaController,
          onChanged: (value) {
            print(value);
            setState(() {
              item['value'] = value;
            });
            saveResult();
          },
          textCapitalization: TextCapitalization.characters,
          // inputFormatters: [
          //   WhitelistingTextInputFormatter(RegExp("[0-9.LT]")), //只允许输入字母
          // ],
          decoration: InputDecoration(
            hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
            border: OutlineInputBorder(
              borderSide: BorderSide.none,
            ),
          ));
    }
    // else if(item['id']=='9000'){
    //   //人车合照
    //   return new Container(height:0);
    // }

    else {
      if (item["post_id"] != "4000") {
        if (item["item"] == "" || item["item"] == null) {
          return new TextField(
              // focusNode: _focusNode3,
              // controller: textEditingController,
              onChanged: (value) {
                print(value);
                setState(() {
                  item['value'] = value;
                });
                saveResult();
              },
              decoration: InputDecoration(
                // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
                hintText: item.containsKey("value") ? item['value'] : '请填写相关信息',
                border: OutlineInputBorder(
                  borderSide: BorderSide.none,
                ),
              ));
        } else {
          //return Container(height:0);

          return checkBox(item);
        }
      } else {
        // return Container(height:0);
        if (item["item"] == "") {
          return new Text('');
        } else {
          //return Container(height:0);
          return checkBox(item);
          // return new Text('');
        }
      }
    }
// item["post_id"] != "4000"
//                     ? item["item"] == ""
//                         ? new TextField(

//                             // controller: textEditingController,
//                             onChanged: (value) {
//                               print(value);
//                               setState(() {
//                                 item['value'] = value;
//                               });
//                             },
//                             decoration: InputDecoration(
//                               hintText: item.containsKey("value")
//                                   ? item['value']
//                                   : '请填写相关信息',
//                               border: OutlineInputBorder(
//                                 borderSide: BorderSide.none,
//                               ),
//                             ))
//                         : checkBox(item)
//                     : item["item"] == "" ? new Text('') : checkBox(item),
  }

  Widget rencheImg(item) {
    List<Widget> tiles = [];
    tiles.add(Padding(
      padding: new EdgeInsets.fromLTRB(10, 20, 0, 10),
      child: GestureDetector(
          onTap: () {
            List temp = [
              ['', item['url']]
            ];
            print(temp);
              Navigator.of(context).push(new FadeRoute(
                        page: GalleryPhotoViewWrapper(
                      galleryItems: imageModelinspectitem(temp),
                      backgroundDecoration: const BoxDecoration(
                        color: Colors.black,
                      ),
                      initialIndex: 1,
                    )));
            // Navigator.of(context).push(
            //   NinePicture(temp, 0),
            // );
          },
          child: Image.network(item['url'], width: 100, height: 100)),
    ));
    var content = new Row(children: tiles);
    return content;
  }

  Widget imgs(item) {
    // item.containsKey("urlArr1")
    //                   ? imgs(item)
    //                   : new Container(height: 0)

    List<Widget> tiles = [];
    Widget content;

    if (item.containsKey("urlArr1")) {
      List items = item["urlArr1"];
      print(items);
      for (var i = 0; i < items.length; i++) {
        List temp1 = items[i] as List;
        tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(5, 10, 5, 10),
          child: GestureDetector(
              onLongPress: () {
                print('识别长按手势');
                showdeleteAlert(item, i);
              },
              onTap: () {
                print('点击查看图片');
                 Navigator.of(context).push(new FadeRoute(
                        page: GalleryPhotoViewWrapper(
                      galleryItems: imageModelinspectitem(items),
                      backgroundDecoration: const BoxDecoration(
                        color: Colors.black,
                      ),
                      initialIndex: i,
                    )));
                // Navigator.of(context).push(
                //   NinePicture(items, i),
                // );
              },
              child: Image.network(temp1[1], width: 100, height: 100)),
        ));
      }
      content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    } else if (item.containsKey("url")) {
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
              print('点击查看图片');
              // Navigator.of(context).push(
              //  // NinePicture(items, i),
              // );
            },
            child: Image.network(item['url'], width: 100, height: 100)),
      ));
    } else {
      tiles.add(Container(height: 0));
    }
    //content = new Row(children: tiles);

    return content;
  }

  showdeleteAlert(obj, index) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
              child: Container(
                height: 130,
                child: new Column(children: <Widget>[
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 50,
                      child: Center(
                          child: Text('是否删除此图片！',
                              style: TextStyle(fontSize: 16)))),
                  new Container(
                      decoration: new BoxDecoration(
                          border: Border(
                              bottom: BorderSide(
                                  width: 1, color: Color(0xffe5e5e5)))),
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () async {
                            //删除图片
                            List imgArr = obj["urlArr1"];
                            imgArr.removeAt(index);
                            setState(() {
                              obj['urlArr1'] = imgArr;
                            });
                            Navigator.pop(context);
                          },
                          child: Center(
                              child: Text('确认删除',
                                  style: TextStyle(
                                      fontSize: 16, color: Colors.red))))),
                  new Container(
                      height: 40,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            Navigator.pop(context);
                          },
                          child: Center(
                              child:
                                  Text('取消', style: TextStyle(fontSize: 16))))),
                ]),
              ));
        });
  }

//复选按钮
  // Widget checkBox_c(item) {
  //   List<Widget> tiles = [];
  //   Widget content;

  //   List<String> items = item["item"].split(',');

  //   //currentExamp["useranswer"] = false;
  //   List<Widget> item = [];
  //   for (var i = 0; i < items.length; i++) {
  //     var radios = items[i];
  //     if (radios != "") {
  //       item.add(CheckboxListTile(
  //           controlAffinity: ListTileControlAffinity.leading,
  //           value: radios["select"],
  //           title: Text(
  //             radios["code"] + "：" + radios["value"],
  //             style: TextStyle(color: Colors.black),
  //           ),
  //           //subtitle: Text("这是二级标题"),

  //           selected: radios["select"],
  //           dense: true,
  //           onChanged: (value) {
  //             setState(() {
  //               // this.flag = value;
  //               radios["select"] = value;
  //               if (value == true) {}
  //             });
  //           }));
  //     }
  //   }
  //   content = new Column(
  //     children: item,
  //     mainAxisAlignment: MainAxisAlignment.spaceAround,
  //     crossAxisAlignment: CrossAxisAlignment.start,
  //   );
  //   return content;
  // }

Widget checkbox1(item, data) {
    List<Widget> tiles = [];
    Widget content;

    // List<String> items = item["item"].split(',');
    List<String> items = data;
    if (true) {
      String defaultv = items[0];
      // if(this.type==2){
      if (select == false) {
        if (item.containsKey("value") == false) {
          item['value'] = defaultv;
        }
      }

      for (var i = 0; i < items.length; i++) {
        var radios = items[i];
        bool checkvalue = false;
        if (item.containsKey('value')) {
          if (item['value'] != '') {
            if (item['value'].endsWith(',')) {
              item['value'] =
                  item['value'].substring(0, item['value'].length - 2);
            }
            List temp = item['value'].split(',');
            checkvalue = temp.contains(radios);
          } else {
            print('没有值');
          }
        }
        //  bool has = RegExp(item['value']).hasMatch(radios);
        if (radios != "") {
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(15, 10, 0, 10),
              child: GestureDetector(
                  onTap: () {
                    if (item.containsKey('value')) {
                      if (radios == items[0]) {
                        setState(() {
                          item['temp_mustimg'] = '0';
                        });
                      } else {
                        setState(() {
                          item['post_id'] == "3000"
                              ? item['temp_mustimg'] = '0'
                              : item['temp_mustimg'] = '1';
                        });
                      }
                      if (item['value'] == "") {
                        setState(() {
                          item['value'] = radios;
                        });
                      } else {
                        if (item['value'] == radios) {
                          setState(() {
                            item['value'] = "";
                          });
                        } else {
                          setState(() {
                            item['value'] = radios;
                          });
                        }
                      }
                    } else {
                      item['value'] = radios;
                    }

                    String code = item["code"];
                    // String code = item["code"];

                    setState(() {
                      // item["value"] = radios;
                      formalities[code] = radios;
                      // paytype = value;
                    });

                    saveResult(); //保存记录
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                    child: Text(
                      radios,
                      style: new TextStyle(
                          fontSize: 11,
                          color: checkvalue == false
                              ? Color.fromRGBO(120, 120, 120, 1)
                              : Colors.white),
                    ),
                    decoration: new BoxDecoration(
                      color: checkvalue == false
                          ? Color.fromRGBO(235, 235, 235, 1)
                          : radios == items[0]
                              ? Colors.blue
                              : item['post_id'] == "3000"
                                  ? Colors.blue
                                  : Colors.red,
                      borderRadius:
                          new BorderRadius.all(new Radius.circular(5.0)),
                    ),
                  ))));
        }
      }
      content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
      //content = new Row(children: tiles);
    }

    return content;
  }


  //单选按钮

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;

    List<String> items = item["item"].split(',');

    if (item['option_type'].toString() == '0') {
      String defaultv = items[0];
      // if(this.type==2){
      if (select == false) {
        if (item.containsKey("value") == false) {
          item['value'] = defaultv;
        }
      }

      for (var i = 0; i < items.length; i++) {
        var radios = items[i];
        bool checkvalue = false;
        if (item.containsKey('value')) {
          if (item['value'] != '') {
            if (item['value'].endsWith(',')) {
              item['value'] =
                  item['value'].substring(0, item['value'].length - 2);
            }
            List temp = item['value'].split(',');
            checkvalue = temp.contains(radios);
          } else {
            print('没有值');
          }
        }
        //  bool has = RegExp(item['value']).hasMatch(radios);
        if (radios != "") {
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(15, 10, 0, 5),
              child: GestureDetector(
                  onTap: () {
                    if (item.containsKey('value')) {
                      if (radios == items[0]) {
                        setState(() {
                          item['temp_mustimg'] = '0';
                        });
                      } else {
                        setState(() {
                          item['post_id'] == "3000"
                              ? item['temp_mustimg'] = '0'
                              : item['temp_mustimg'] = '1';
                        });
                      }
                      if (item['value'] == "") {
                        setState(() {
                          item['value'] = radios;
                        });
                      } else {
                        if (item['value'] == radios) {
                          setState(() {
                            item['value'] = "";
                          });
                        } else {
                          setState(() {
                            item['value'] = radios;
                          });
                        }
                      }
                    } else {
                      item['value'] = radios;
                    }

                    saveResult(); //保存记录
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
                    child: Text(
                      radios,
                      style: new TextStyle(
                          fontSize: 11,
                          color: checkvalue == false
                              ? Color.fromRGBO(120, 120, 120, 1)
                              : Colors.white),
                    ),
                    decoration: new BoxDecoration(
                      color: checkvalue == false
                          ? Color.fromRGBO(235, 235, 235, 1)
                          : radios == items[0]
                              ? Colors.blue
                              : item['post_id'] == "3000"
                                  ? Colors.blue
                                  : Colors.red,
                      borderRadius:
                          new BorderRadius.all(new Radius.circular(5.0)),
                    ),
                  ))));
        }
      }
      content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
      //content = new Row(children: tiles);
    } else {
      for (var i = 0; i < items.length; i++) {
        var radios = items[i];
        bool checkvalue = false;
        if (item.containsKey('value')) {
          if (item['value'] != '') {
            // if (item['value'].endsWith(',')) {
            //   item['value'] =
            //       item['value'].substring(0, item['value'].length - 2);
            // }
            List temp = item['value'].split(',');
            checkvalue = temp.contains(radios);
          } else {}
        }
        //  bool has = RegExp(item['value']).hasMatch(radios);
        if (radios != "") {
          tiles.add(Padding(
              padding: new EdgeInsets.fromLTRB(15, 10, 0, 5),
              child: GestureDetector(
                  onTap: () {
                    if (radios == '正常') {
                      if (item['value'] == '正常') {
                        setState(() {
                          item['value'] = ""; //选择正常时，清空其他选项，并且赋值
                          item['temp_mustimg'] = '0';
                        });
                      } else {
                        setState(() {
                          item['value'] = radios; //选择正常时，清空其他选项，并且赋值
                          item['temp_mustimg'] = '0';
                        });
                      }
                    } else {
                      if (item['value'] == '正常') {
                        setState(() {
                          item['temp_mustimg'] = '0';
                        });
                        //选择其他选项时，先判断是否选择了正常
                        return;
                      } else {
                        if (checkvalue == false) {
                          setState(() {
                            if (item.containsKey('value')) {
                              if (item['value'] == "") {
                                item['value'] = radios;
                              } else {
                                item['value'] = item['value'] + ',' + radios;
                              }
                            } else {
                              item['value'] = radios;
                            }
                            // item['value'] = item.containsKey('value')
                            //     ? item['value']+ ',' + radios
                            //     : radios ;
                            item['temp_mustimg'] = '1';
                          });
                        } else {
                          List temp = item['value'].split(',');
                          temp.remove(radios);
                          String tempstr = "";
                          temp.forEach((element) {
                            if (tempstr == "")
                              tempstr = element;
                            else
                              tempstr = tempstr + ',' + element;
                            //tempstr = "$tempstr" "," "$element";
                          });

                          setState(() {
                            item['value'] = tempstr;
                          });
                        }
                      }
                    }
                    saveResult(); //保存记录
                  },
                  child: Container(
                    // alignment: alin,
                    // padding: new EdgeInsets.fromLTRB(10, 8, 10, 8),
                    padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10),
                    child: Text(
                      radios,
                      style: new TextStyle(
                          fontSize: 11,
                          color: checkvalue == false
                              ? Color.fromRGBO(120, 120, 120, 1)
                              : Colors.white),
                    ),

                    decoration: new BoxDecoration(
                      // border: new Border.all(width: 2.0, color: Colors.red),
                      color: checkvalue == false
                          ? Color.fromRGBO(235, 235, 235, 1)
                          : radios == items[0] ? Colors.blue : Colors.red,
                      borderRadius:
                          new BorderRadius.all(new Radius.circular(5.0)),
                    ),
                  ))));
          // tiles.add(CheckboxListTile(
          //     controlAffinity: ListTileControlAffinity.leading,
          //     value: checkvalue,
          //     activeColor: Colors.blue,
          //     title: Text(
          //       radios,
          //      style: new TextStyle(
          //                 fontSize: 11,
          //                 color: Color.fromRGBO(100, 100, 100, 1)),
          //     ),
          //     //subtitle: Text("这是二级标题"),
          //     dense: true,
          //     onChanged: (value) {
          //       //真他妈难写
          //       if (value == true) {
          //         if (radios == '正常') {
          //           setState(() {
          //             item['value'] = radios; //选择正常时，清空其他选项，并且赋值
          //             item['temp_mustimg'] = '0';
          //           });
          //         } else {
          //           if (item['value'] == '正常') {
          //             setState(() {
          //               item['temp_mustimg'] = '0';
          //             });
          //             //选择其他选项时，先判断是否选择了正常
          //             return;
          //           } else {
          //             setState(() {
          //               if (item.containsKey('value')) {
          //                 if (item['value'] == "") {
          //                   item['value'] = radios;
          //                 } else {
          //                   item['value'] = item['value'] + ',' + radios;
          //                 }
          //               } else {
          //                 item['value'] = radios;
          //               }
          //               // item['value'] = item.containsKey('value')
          //               //     ? item['value']+ ',' + radios
          //               //     : radios ;
          //               item['temp_mustimg'] = '1';
          //             });
          //           }
          //         }
          //       } else {
          //         if (radios == "正常") {
          //           setState(() {
          //             item['value'] = ""; //选择正常时，清value
          //             item['temp_mustimg'] = '0';
          //           });
          //         } else {
          //           List temp = item['value'].split(',');
          //           temp.remove(radios);
          //           String tempstr = "";
          //           temp.forEach((element) {
          //             if (tempstr == "")
          //               tempstr = element;
          //             else
          //               tempstr = tempstr + ',' + element;
          //             //tempstr = "$tempstr" "," "$element";
          //           });

          //           setState(() {
          //             item['value'] = tempstr;
          //           });
          //         }
          //       }
          //       saveResult();
          //  }
          //  )
          // );
        }
      }
      content = new Wrap(spacing: 5, runSpacing: 0, children: tiles);
      // content = new Column(
      //   children: tiles,
      //   mainAxisAlignment: MainAxisAlignment.spaceAround,
      //   crossAxisAlignment: CrossAxisAlignment.start,
      // );
    }

    return content;
  }

  backhome() {
    if (role == 1) {
      final PageRouteBuilder _homeRoute = new PageRouteBuilder(
        pageBuilder: (BuildContext context, _, __) {
          return UBotomeMenumPage();
        },
      );
      Navigator.pushAndRemoveUntil(
          context, _homeRoute, (Route<dynamic> r) => false);
    } else {
      // return new BotomeMenumPage();
      final PageRouteBuilder _homeRoute = new PageRouteBuilder(
        pageBuilder: (BuildContext context, _, __) {
          return BotomeMenumPage();
        },
      );
      Navigator.pushAndRemoveUntil(
          context, _homeRoute, (Route<dynamic> r) => false);
    }
  }

  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        //  resizeToAvoidBottomPadding:resize,
        key: _scaffoldKey,
        appBar: appBar,
        floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            backhome();
          },
          child: Icon(
            Icons.home,
            color: Colors.white,
          ),
          backgroundColor: Colours.app_main,
        ),
        body: Container(
          height: 800,
          color: Colors.white,
          child: Stack(children: <Widget>[
            loaddata
                ? Padding(
                    padding: new EdgeInsets.fromLTRB(0, 0, 0, 110),
                    child: ListView(
                      controller: scrollController,
                      children: _buildList(),
                    ))
                : new Text(''),
            Positioned(
              left: 0,
              right: 0,
              bottom: 0,
              // alignment: Alignment.bottomCenter,
              child: Padding(
                padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
                // child: Container(
                //   width: double.infinity,
                //   color: Color.fromRGBO(27, 182, 251, 1),
                child: new FlatButton(
                    color: Color.fromRGBO(27, 182, 251, 1),
                    shape: RoundedRectangleBorder(
                        side: BorderSide.none,
                        borderRadius: BorderRadius.all(Radius.circular(20))),
                    onPressed: () {
                      // connect();
                      // subOrder(0);
                      alertfinsh();
                      //prepdf();
                    },
                    child: new Text(
                      '检测完成？提交',
                      style: TextStyle(color: Colors.white),
                    )),
              ),
              //)
            ),
            Positioned(
                left: 0,
                right: 0,
                bottom: 50,
                // alignment: Alignment.bottomCenter,
                child: Padding(
                  padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
                  child: Container(
                      width: double.infinity,
                      // height: 50,
                      // color: Color.fromRGBO(27, 182, 251, 1),
                      child: new Row(
                        children: <Widget>[
                          Expanded(
                              flex: 1,
                              // child: Align(
                              //   // alignment: Alignment.bottomRight,
                              child: Padding(
                                  padding:
                                      new EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  child: new FlatButton(
                                      shape: RoundedRectangleBorder(
                                          side: BorderSide.none,
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(20))),
                                      color: Color.fromRGBO(27, 182, 251, 1),
                                      onPressed: () {
                                        setState(() {
                                          savebtn = true;
                                        });
                                        saveResult();
                                      },
                                      child: new Text(
                                        '保存',
                                        style: TextStyle(color: Colors.white),
                                      )))),
                          //),
                          Expanded(
                              flex: 1,
                              child: Padding(
                                  padding:
                                      new EdgeInsets.fromLTRB(10, 0, 10, 0),
                                  child:
                                      // Align(
                                      //   // alignment: Alignment.bottomLeft,

                                      //     child:
                                      new FlatButton(
                                    shape: RoundedRectangleBorder(
                                        side: BorderSide.none,
                                        borderRadius: BorderRadius.all(
                                            Radius.circular(20))),
                                    color: Color.fromRGBO(225, 102, 82, 1),
                                    onPressed: () {
                                      prepdf();
                                    },
                                    child: new Text('预览报告',
                                        style: TextStyle(color: Colors.white)),
                                  ))),
                          //),
                          // Expanded(
                          //     flex: 1,
                          //     child: Align(
                          //       alignment: Alignment.bottomLeft,
                          //         child: new FlatButton(
                          //       color: Color.fromRGBO(27, 182, 251, 1),
                          //       onPressed: () {
                          //         alertfinsh();
                          //       },
                          //       child: new Text('提交',
                          //           style: TextStyle(color: Colors.white)),
                          //     ))),
                        ],
                      )
                      // child: new FlatButton(
                      //     onPressed: () {
                      //       // connect();
                      //       // subOrder(0);
                      //       // alertfinsh();
                      //       prepdf();
                      //     },
                      //     child: new Text(
                      //       '报告预览',
                      //       style: TextStyle(color: Colors.white),
                      //     )),
                      ),
                )),
          ]),
        ),
      ),
      onWillPop: () => willpop(),
    );
  }

  //报告预览
  prepdf() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');

    String url = HttpHelper.host +
        '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.b_test_reports&id=' +
        this.oid +
        '&ismobile=1';
    if (role.toString() == '1') {
      //用户的报告连接

      // if(order_info['test_type']=="金融检测"){
      //                           //assement
      //                           url = HttpHelper.host +
      //                             '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.assement&id=' +
      //                             this.oid ;
      //                         }
      // url = HttpHelper.host +
      //     '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_reports&id=' +
      //     this.oid +
      //     '&ismobile=1';
      url = HttpHelper.host +
          '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.assement&id=' +
          this.oid +
          '&ismobile=1';
    }
    Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
      return new preWebPage(url, this.oid);
    }));
  }

//  Future<bool> willpop() {
//     setstate(){
//       seconds=1;
//     };
//     return Future.value(false);
//   }

  alertfinsh() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('是否已全部项目检测完成?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context, rootNavigator: true).pop();
                    subOrder(0);
                    // Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }

  //提交检测项
  subOrder(types) {
    FocusScope.of(context).requestFocus(FocusNode());


    if(chejiaController.text.length!=17){
      Toast.show('请填写正确的车架号', context);
      return;
    }

    // if (this.orderStatus == "0"||this.orderStatus == "1") {
    Map<String, Object> map = new Map();
    map["oid"] = this.oid;
    map["type"] = '3';
    if (types == 1) {
      for (var item in testItem) {
        for (var items in item["post"]) {
          if (items["show_report"] == "是") {
            items["show_report"] = "1";
          }
          if (items["show_report"] == "否") {
            items["show_report"] = "0";
          }
        }
      }
    }
    Map chechdata1 = {"checkData": testItem};
    Map picinspects = new Map();

    for (var item in testItem) {
      if (item['id'] == '4000') {
        //照片和检测项分开
        picinspects = item;
        //testItem.remove(item);
      }
      if (item['id'] == '3000') {
        for (var k in item["post"]) {
          if (k["id"] == "3029") {
            //车牌信息单独写入
            k['value'] = pwdData;
          }
        }
      }
    }
    if (role == 1) {
      List tempImg = picinspects['post'];
      bool hasrenche = false;
      tempImg.forEach((element) {
        if (element['name'] == "人车合照") {
          hasrenche = true;
        }
      });
      if (picParam.length > 0 && !hasrenche) picinspects['post'].add(picParam);
      // if (picParam.length > 0) picinspects['post'].add(picParam);
      // if (orderInfo["is_start"] == "0") {
      //   picinspects['post'].add(picParam);
      // }
    } //��加人车合照

    //将手续信息里面的图片增加到手续对象里面
    //将手续信息里面的图片增加到手续对象里面
    List temp = new List();
    for (var i = 0; i < formList.length; i++) {
      var item = formList[i];
      if (item["urlArr1"].length > 0) {
        temp.add({
          "title": item['title'],
          'sub_title': '云A00001云A00001云A00',
          // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
          'type': item['type'],
          "code": item['code'],
          "value": "",
          "mustimg": 1,
          'urlArr1': item['urlArr1'],
          'urlArr': item['urlArr'],
          'hasimg': 0,
        });
      }
    }
    formalities['images'] = temp;

    if (resultPriceController.text == "") {
      Toast.show('请填写最终评估价格', context);
      return;
    }
    // if (weituoController.text == "") {
    //   Toast.show('请填写委托人信息', context);
    //   return;
    // }

    Map checkdata = {
      "otherData": chechdata1,
      // "formalities": {'data':formList},
      "formalities": formalities,
      'result': Checkresult,
      "pics": picinspects,
      'result_price': resultPriceController.text
    };
    if (types == 1) {
      //生成报告单时，手续信息不变
      checkdata = {
        "otherData": chechdata1,
        "formalities": oldformalities,
        'result': Checkresult,
        "pics": picinspects
      };
    }
    // checkdata["otherData"]["checkData"]=testItem;
    // map["inspector"] = jsonEncode(testItem);
    map["inspector"] = jsonEncode(checkdata);

    map["brand"] = current_brand; //品牌
    map["cartype"] = current_type; //车型单独更新
    // print('传递的检测项');
    print(map);
    HttpHelper.post(HttpHelper.API_SubOrder, (data) async {
      if (data != null) {
        print(data);
        if (data["code"].toString() == "1") {
          Toast.show('检测完成，可查看报告', context);

          if (connectBluetooth) {
            flutterBlue.stopScan();
            device.disconnect(); //退出就断开蓝牙
          } else {
            flutterBlue.stopScan();
          }
          Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
            return new PapularinspectReults(this.oid, this.type);
          }));

          // Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
          //   return new PapularinspectReults(this.oid, this.type);
          // }));
        } else {
          Toast.show(data["msg"], context);
        }
      }
    }, params: map);
    // }
  }

//定时保存结果
  saveResult() async {
    print('触发���时保存');
    //查看车架号
    // if(chejiaController.text.length!=17){
    //   Toast.show('请填写正确的车架号', context);
    //   return;
    // }
    Map<String, Object> map = new Map();
    map["oid"] = this.oid;
    map["type"] = this.type.toString();
    map['brand'] = current_brand;
    map['cartype'] = current_type;

    Map chechdata1 = {"checkData": testItem};
    Map picinspects = new Map();

    int hasvalue1 = 0; //检测项已填数目
    int hasvalue2 = 0; //照片已填数目
    int hasvalue3 = 0; //手续信息已填数目
    for (var item in testItem) {
      if (item['id'] == '4000') {
        //照片和检测项分开
        picinspects = item;
        //testItem.remove(item);
      }
      if (item['id'] == '3000') {
        for (var k in item["post"]) {
          if (k["id"] == "3029") {
            //车牌信息单独写入
            k['value'] = pwdData;
          }
        }
      }
    }
    // if (role == 1) picinspects['post'].add(picParam); //增加人��合照

//将手续信息里面的图片增加到手���对象里面
    List temp = new List();
    for (var i = 0; i < formList.length; i++) {
      var item = formList[i];
      if (item["urlArr1"].length > 0) {
        temp.add({
          "title": item['title'],
          'sub_title': '云A00001云A00001云A00',
          // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
          'type': item['type'],
          "code": item['code'],
          "value": "",
          "mustimg": 1,
          'urlArr1': item['urlArr1'],
          'urlArr': item['urlArr'],
          'hasimg': 0,
        });
      }
    }
    formalities['images'] = temp;
    //formalities['images'] = [{'id':'1'}];
    Map checkdata = {
      "otherData": chechdata1,
      "formalities": formalities,
      'result': Checkresult,
      'result_price': resultPriceController.text,
      "pics": picinspects,
      "order_id": this.oid
      //'formalities1':{"images":formList}

      // "formalities_img":jsonEncode(formalities)
    };

    // checkdata["otherData"]["checkData"]=testItem;
    // map["inspector"] = jsonEncode(testItem);
    map["inspector"] = jsonEncode(checkdata);
    //
    SharedPreferences pref = await SharedPreferences.getInstance();
    List<String> order = [];
    if (pref.getStringList('orders') != null) {
      order = pref.getStringList('orders');
    }
    if (order.length > 0) {
      for (var i = 0; i < order.length; i++) {
        Map result = jsonDecode(order[i]);
        if (result['order_id'] == this.oid) {
          //
          order.replaceRange(i, i + 1, [jsonEncode(checkdata)]);
        }
      }
    } else {
      order.add(jsonEncode(checkdata));
    }
    pref.setStringList('orders', order);
    // print('传递的检测项');

    String role = pref.getString('role');
    if (role.toString() != "1") {
      map['isbuss'] = '1';
    }

    map['sub'] = '1';

    HttpHelper.postUrl(HttpHelper.API_SaveResult, context, (data) async {
      print(data);
      if (savebtn == true && data['code'].toString() == "1") {
        Toast.show(data['msg'], context);
      }
      if (data['code'].toString() == "-1") {
        Toast.show(data['msg'], context);
      }
      setState(() {
        savebtn = false;
      });
    }, params: map);
  }

  cacheinfo() {}

  List<Widget> _buildList() {
    List<Widget> widgets = [];
    widgets.add(buildcontents());
    for (var item in testItem) {
      widgets.add(buildcontent(item));
    }

    widgets.add(
      new Container(
          child: new Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
        child: TextField(
          focusNode: _focusNode4,
          maxLines: 5,
          controller: resultController,
          onChanged: (value) {
            setState(() {
              Checkresult = value;
              resize = true;
            });
            saveResult();
          },
          decoration: InputDecoration(
              // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
              border: InputBorder.none,
              fillColor: Color.fromRGBO(238, 238, 238, 1),
              filled: true,
              labelStyle: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),
              labelText: '输入最终检测结论'),
        ),
      )),
    );
    widgets.add(
      new Container(
          child: new Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
        child: TextField(
          // focusNode: _focusNode4,
          maxLines: 1,
          controller: resultPriceController,
          onChanged: (value) {
            setState(() {
              // Checkresult = value;
              resize = true;
            });
            saveResult();
          },
          inputFormatters: [
            // LengthLimitingTextInputFormatter(17), //长度限制17位
            WhitelistingTextInputFormatter(RegExp("[0-9.]")), //只允许数字
          ],
          decoration: InputDecoration(
              // contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
              border: InputBorder.none,
              fillColor: Color.fromRGBO(238, 238, 238, 1),
              filled: true,
              labelStyle: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),
              labelText: '输入预估价格（万）'),
        ),
      )),
    );
    // this._cityNames.keys.forEach((key) {
    //   widgets.add(_item(key, _cityNames[key]));
    // });
    return widgets;
  }

  Widget _item(String city, List<String> subCities) {
    return ExpansionTile(
        children: subCities.map((subCity) => _buildSub(subCity)).toList(),
        title: Text(
          city,
          style: TextStyle(
            color: Colors.black54,
            fontSize: 20,
          ),
        ));
  }

  Widget _buildSub(String subCity) {
    return FractionallySizedBox(
      widthFactor: 1,
      child: Container(
        height: 40,
        margin: EdgeInsets.only(bottom: 5, left: 12),
        //decoration: BoxDecoration(color: Colors.grey),
        child: Text(
          subCity,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

//灯光异常图片
  Widget showLightBProblem(itemid, postdata, type) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/model/light/light_b.png";

    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    // if (type == 1) {
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );
    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      var id = item["id"];
      List<String> items = item["item"].split(',');

      String urls = '';
      for (int n = 0; n < items.length; n++) {
        if (item["value"] == items[n]) {
          if (n == 0) continue;
          if (int.parse(id) < 4010 && int.parse(id) != 4016) continue;
          //urls = 'resource/images/jiance/model/boli/40202.png';
          urls = 'resource/images/jiance/model/light/' +
              id.toString() +
              '-' +
              n.toString() +
              '.png';
          try {
            tiles.add(
              Positioned(child: new Image.asset(urls)),
            );
          } catch (e) {}
        }
        print(urls);
      }
    }

    // }

    content = new Stack(children: tiles);
    return content;
  }

  //灯光异常图片
  Widget showLightProblem(itemid, postdata, type) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/model/light/light_f.png";

    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    // if (type == 1) {
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );
    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      var id = item["id"];
      List<String> items = item["item"].split(',');
      String urls = '';
      for (int n = 0; n < items.length; n++) {
        if (item["value"] == items[n]) {
          if (n == 0) continue;

          if (int.parse(id) > 4009 && int.parse(id) != 4016) continue;
          //urls = 'resource/images/jiance/model/boli/40202.png';
          urls = 'resource/images/jiance/model/light/' +
              id.toString() +
              '-' +
              n.toString() +
              '.png';
          try {
            tiles.add(
              Positioned(child: new Image.asset(urls)),
            );
          } catch (e) {}
        }
      }
    }

    content = new Stack(children: tiles);
    return content;
  }

  //异常图片
  Widget showProblem(itemid, postdata) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/carmodel2.png";
    if (itemid == "3043") {
      //结构件
      modelUrl = "resource/images/jiance/model/jiegou/jiegou.jpg";
    } else if (itemid == "3044") {
      //浸泡检测
      modelUrl = "resource/images/jiance/qinpao.png";
    } else if (itemid == "3076") {
      //车身玻璃
      modelUrl = "resource/images/jiance/model/boli/boli.png";
    }
    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );

    if (itemid != "3044") {
      //浸泡检测不需要实时图片
      // List postData = param["post"];
      for (var i = 0; i < postdata.length; i++) {
        var item = postdata[i];
        List<String> items = item["item"].split(',');

        var id = item["id"];
        // print(id);
        if (item.containsKey("value")) {
          if (item["post_id"] == "3076") {
            String urls;
            for (int n = 0; n < items.length; n++) {
              if (item["value"] == items[n]) {
                if (n == 0) continue;
                //urls = 'resource/images/jiance/model/boli/40202.png';
                urls = 'resource/images/jiance/model/boli/' +
                    id.toString() +
                    '-' +
                    n.toString() +
                    '.png';
              }
            }
            if (item["value"] != items[0]) {
              // File imgs = File(urls);
              // var dir_bool = imgs.exists();
              // print(dir_bool);
              //print(urls);
              try {
                tiles.add(
                  Positioned(child: new Image.asset(urls)),
                );
              } catch (e) {
                print(e);
              }
            }
          } else {
            if (items[0] != item["value"]) {
              //有异常情况
              String urls;
              if (item["post_id"] == "3043") {
                urls = 'resource/images/jiance/model/jiegou/' +
                    id.toString() +
                    '.png';
              } else {
                //漆面检测
                for (int n = 0; n < items.length; n++) {
                  if (item["value"] == items[n]) {
                    if (n == 0) continue;
                    int tempv = 1;
                    if (n == 1) {
                      tempv = 2;
                    }
                    urls = 'resource/images/jiance/model/qimian/' +
                        id.toString() +
                        '-' +
                        tempv.toString() +
                        '.png';
                    //urls = 'resource/images/jiance/model/boli/40202.png';
                    // urls = 'resource/images/jiance/model/boli/' +
                    //     id.toString() +
                    //     '-' +
                    //     n.toString() +
                    //     '.png';
                  }
                }
                // urls = 'resource/images/jiance/model/qimian/' +
                //     id.toString() +
                //     '.png';
              }

              //File imgs = File(urls);
              // var dir_bool = imgs.exists();
              // print(dir_bool);
              //print(urls);

              try {
                tiles.add(
                  Positioned(child: new Image.asset(urls)),
                );
              } catch (e) {
                print(e);
              }
            }
          }
        }
      }
    }
    content = new Stack(children: tiles);
    return content;
  }

  //手续信息单独处理
  Widget itemContent(item) {
    var child;
    if (item["type"] == "0") {
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
          child:checkbox1(item, ['有','无','未见']),
          // child: Row(
          //   // crossAxisAlignment: CrossAxisAlignment.end,
          //   mainAxisAlignment: MainAxisAlignment.end,
          //   children: <Widget>[
          //     Radio<String>(
          //         //当前Radio的值
          //         hoverColor: Color.fromRGBO(200, 200, 200, 1),
          //         focusColor: Color.fromRGBO(25, 172, 249, 1),
          //         value: "有",
          //         activeColor: Color.fromRGBO(25, 172, 249, 1),
          //         groupValue: item["value"],
          //         // groupValue: defaultv,
          //         onChanged: (value) {
          //           String code = item["code"];
          //           // String code = item["code"];

          //           setState(() {
          //             item["value"] = value;
          //             formalities[code] = value;
          //             // paytype = value;
          //           });
          //           saveResult();
          //         }),
          //     new Text("有",
          //         style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
          //     Radio<String>(
          //         //当前Radio的值
          //         hoverColor: Color.fromRGBO(200, 200, 200, 1),
          //         focusColor: Color.fromRGBO(25, 172, 249, 1),
          //         value: "无",
          //         activeColor: Color.fromRGBO(25, 172, 249, 1),
          //         groupValue: item["value"],
          //         // groupValue: defaultv,
          //         onChanged: (value) {
          //           // String code = item["code"];
          //           String code = item["code"];
          //           // item["value"] = value;
          //           // formalities[code] = value;
          //           setState(() {
          //             item["value"] = value;
          //             formalities[code] = value;
          //           });
          //           saveResult();
          //         }),
          //     new Text("无",
          //         style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
          //   ],
          // )
          );
    } else if (item["type"] == "1") {
      //时间选择组件
      DateTime initialDate = DateTime.now();
      child = new GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () async {
            FocusScope.of(context).requestFocus(FocusNode());
            _showDatePicker(item);
          },
          child: Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
              child: Align(
                alignment: Alignment.centerRight,
                child: new Text(item["value"] == "" ? '选择日期' : item["value"]),
              )));
    }
     else if (item["type"] == "100") {
      //时间选择组件
      DateTime initialDate = DateTime.now();
      child = Row(
          //crossAxisAlignment:CrossAxisAlignment.s,
          //  mainAxisAlignment:MainAxisAlignment.end,
          //  crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            new GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () async {
                  FocusScope.of(context).requestFocus(FocusNode());
                  _showDatePicker(item);
                },
                child: Padding(
                    padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                    child: Align(
                      alignment: Alignment.centerRight,
                      child: new Text(
                        
                          item["value"] == "" ? '选择日期' : item["value"]),
                    ))),
             Spacer(),
            //Container(width: 20,),
            Align(
                alignment: Alignment.centerRight,
                child: InkWell(
                    child:
                    Padding(padding: new EdgeInsets.fromLTRB(0, 0, 20, 0),child:
                     Text("未见", style: TextStyle(color: Colors.black,fontWeight:FontWeight.w500))),
                    onTap: () {
                      String code = item["code"];
                      setState(() {
                        item["value"] = "未见";
                        formalities[code] = item["value"];
                      });
                    }))
          ]);
    }
     else if (item["type"] == "2") {
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 20, 0),
          child: new TextField(
              controller: item['controller'],
              //focusNode: _focusNode5,
              onChanged: (value) {
                String code = item["code"];
                item["value"] = value;
                formalities[code] = value;
                saveResult(); //输入框触发保存
              },
              textAlign: TextAlign.right,
              keyboardType: item["code"] == "transfer"
                  ? TextInputType.number
                  : TextInputType.text,
              //controller: _validtroller,
              decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(vertical: 4.0),
                  hintText: item["value"] == "" ? '请填写信息' : item["value"],
                  border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                  ))));
    } else if (item["type"] == "3") {
      child = Switch(
        //当前状态
        value: item["value"] == "是" ? true : false,
        // 激活时原点颜色
        activeColor: Colors.blue,
        inactiveTrackColor: Colors.blue.shade50,
        onChanged: (value) {
          //重新构建页面
          setState(() {
            String code = item["code"];
            item["value"] = value == true ? "是" : "否";
            formalities[code] = value;
          });
        },
      );
    } else if (item["type"] == "4") {
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 20, 0),
          child: Align(
              alignment: Alignment.centerRight,
              child: new GestureDetector(
                  child: new Text(item["value"] == "" ? '请选择' : item["value"]),
                  onTap: () async {
                    int types = 1;
                    if (item['code'] == "specialcar") types = 2;
                    FocusScope.of(context).requestFocus(FocusNode());
                    Navigator.push<Object>(context,
                        new MaterialPageRoute(builder: (BuildContext context) {
                      return Insurance_Page(item, types);
                    })).then((Object result) {
                      String code = item["code"];
                      formalities[code] = item["value"];
                      saveResult();
                    });
                  })));
    }

    if (item["type"] == "3") {
      return new Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child);
    } else {
      return Expanded(
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child));
    }
  }

  //选择日期组件
  void _showDatePicker(item) {
    print('选择日期');
    DatePicker.showDatePicker(
      context,
      onMonthChangeStartWithFirstDate: true,
      pickerTheme: DateTimePickerTheme(
        showTitle: true,
        confirm: Text('确定', style: TextStyle(color: Colors.red)),
        cancel: Text('取消', style: TextStyle(color: Colors.cyan)),
      ),
      minDateTime: DateTime.parse(MIN_DATETIME),
      maxDateTime: DateTime.parse(MAX_DATETIME),
      initialDateTime: _dateTime,
      dateFormat: _format,
      locale: _locale,
      onClose: () => print("----- onClose -----"),
      onCancel: () => print('onCancel'),
      onChange: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          _dateTime = dateTime;
        });
      },
      onConfirm: (dateTime, List<int> index) {
        print(dateTime);
        setState(() {
          String code = item["code"];
          item["value"] = formatDate(dateTime, [yyyy, "-", mm, "-", dd]);
          formalities[code] = item["value"];
        });
        print(item);
        setState(() {
          _dateTime = dateTime;
        });
        saveResult(); //触发保存
      },
    );
  }

  Widget buildcontents() {
    List<Widget> tiles = [];
    Widget content;
    int counters = 0;
    for (var item in formList) {
      if (item.containsKey('value')) {
        if (item["value"] != "") {
          counters++;
        }
      }
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
              color: Colors.white,
              // height: item["urlArr1"].length > 0 ? 170 : 50,
              child: new Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        height: 50,
                        child: new Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Expanded(
                                child: new Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(15, 0, 10, 0),
                                    child: Align(
                                        alignment: Alignment.centerLeft,
                                        child: new Text(
                                          item['title'],
                                          style: TextStyle(
                                              fontWeight: FontWeight.w600,
                                              fontSize: 14,
                                              color: Color.fromRGBO(
                                                  102, 102, 102, 1)),
                                        )))),
                            item['mustimg'] == 1
                                ? Padding(
                                    padding:
                                        new EdgeInsets.fromLTRB(10, 0, 0, 0),
                                    child: new GestureDetector(
                                        onTap: () {
                                          FocusScope.of(context)
                                              .requestFocus(FocusNode());
                                          photo(item);
                                        },
                                        child: new Image.asset(
                                          'resource/images/user/cremra.png',
                                          width: 20,
                                          height: 20,
                                          fit: BoxFit.contain,
                                        )))
                                : new Container(height: 0),
                            itemContent(item)
                            // status == "0" || status == "1"
                            //     ? itemContent(item)
                            //     : Expanded(
                            //         child: Padding(
                            //             padding: new EdgeInsets.fromLTRB(
                            //                 0, 0, 15, 0),
                            //             child: Align(
                            //                 alignment: Alignment.centerRight,
                            //                 child: new Text(item["value"]))))
                            // Expanded(
                            //   child: new Padding(
                            //       padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                            //       child: new TextField(
                            //           textAlign: TextAlign.right,
                            //           //controller: _validtroller,
                            //           decoration: InputDecoration(
                            //             hintText: '验证码',
                            //             border: OutlineInputBorder(
                            //               borderSide: BorderSide.none,
                            //             ),
                            //           ))),
                            // child: new Text(
                            //   item['sub_title'],
                            //   style:
                            //       TextStyle(fontSize: 15, color: item['sub_color']),
                            // )),
                            //)
                          ],
                        )),
                    item["hasimg"] != 0 ? imgs(item) : Container(height: 0)
                  ]))));
    }
    return ExpansionTile(
      onExpansionChanged: (value) {
        print('点击了展开列表');
        print(value);
      },
      children: tiles,
      title: RichText(
          text: TextSpan(
              text: '手续信息',
              style: TextStyle(fontSize: 16.0, color: Colors.black,fontWeight:FontWeight.w600),
              children: <TextSpan>[
            TextSpan(
                text: '*', style: TextStyle(fontSize: 18.0, color: Colors.red)),
            TextSpan(
                text: "（" +
                    counters.toString() +
                    '/' +
                    formList.length.toString() +
                    '）',
                style: TextStyle(fontSize: 12.0, color: Colors.red))
          ])),
      // title: Text(
      //   item["name"],
      //   style: TextStyle(
      //     color: Colors.black,
      //     fontSize: 16,
      //   ),
      // )
    );
    // content = new Column(
    //     children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
    //     //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
    //     );
    // return content;
  }

//16进制转换成10进制数值
  int _hexToInt(String hex) {
    int val = 0;
    int len = hex.length;
    for (int i = 0; i < len; i++) {
      int hexDigit = hex.codeUnitAt(i);
      if (hexDigit >= 48 && hexDigit <= 57) {
        val += (hexDigit - 48) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 65 && hexDigit <= 70) {
        // A..F
        val += (hexDigit - 55) * (1 << (4 * (len - 1 - i)));
      } else if (hexDigit >= 97 && hexDigit <= 102) {
        // a..f
        val += (hexDigit - 87) * (1 << (4 * (len - 1 - i)));
      } else {
        throw new FormatException("Invalid hexadecimal value");
      }
    }
    return val;
  }

  //车牌输入法
  void _showBottomSheet() {
    print('键盘��现');
    setState(() {
      showkb = true;
    });
    if (pwdData == "输入车牌") {
      setState(() {});
    }
    // new NumberKeyboardActionSheet(name: "1111", controller: car_num);
    setState(() {
      // disable the button  // 禁用按钮
      _showBottomSheetCallback = null;
    });

    /*
      currentState：获取具有此全局键的树中的控件状态
      showBottomSheet：显示持久性的质感设计底部面板
      解释：联系上文，_scaffoldKey是Scaffold框架状态的唯一键，因此代码大意为，
           在Scaffold框架中显示持久性的质感设计底部面���
     */
    _scaffoldKey.currentState
        .showBottomSheet<void>((BuildContext context) {
          /// 将自定义的密码键盘作为其child   这里将回调函数传入
          return new board.MyKeyboard(_onKeyDown, pwdData);
        })
        .closed
        .whenComplete(() {
          if (mounted) {
            setState(() {
              // re-enable the button  // 重新启用按钮
              _showBottomSheetCallback = _showBottomSheet;
            });
          }
        });
  }

  /// 密码键盘的整体回调���根据不同的按钮事件来进行相应的逻辑实现
  void _onKeyDown(board. KeyEvent data) {
    print("删除前车牌：" + pwdData);
// 如果点击了删除按钮，则将密码进行��改
    if (data.isDelete()) {
      if (pwdData != "输入车牌") {
        if (pwdData.length > 0) {
          pwdData = pwdData.substring(0, pwdData.length - 1);
          setState(() {});
        }
      }
      if (pwdData.length == 0) {
        setState(() {
          pwdData = "输入车牌";
        });
      }
    }
// 点击了确定按钮时
    else if (data.isCommit()) {
      print("点击完成");
      setState(() {
        pwdData = pwdData;
        showkb = false;
      });
      Navigator.of(context).pop();
//      if (pwdData.length != 7) {
////        Fluttertoast.showToast(msg: "密码不足6位，请重试", gravity: ToastGravity.CENTER);
//        return;
//      }
      // onAffirmButton();
    }
//点击了数��按钮时  将密码进行��整的拼接
    else {
      if (pwdData.length == 0) {}
      if (pwdData == "输入车牌") {
        setState(() {
          pwdData = "";
        });
      }
      if (pwdData.length < 7) {
        pwdData += data.key;
      }
      if (pwdData.length == 7 || pwdData.length > 7) {
        if (showkb == true) {
          Navigator.of(context).pop();
          setState(() {
            showkb = false;
          });
        }
      }
      setState(() {
        pwdData = pwdData;
      });
    }
  }

  Future<bool> willpop() {
    setState(() {
      seconds = 1; //取消计时器
    });
    print('退出');
    if (connectBluetooth) {
      flutterBlue.stopScan();
      device.disconnect(); //退出就断开蓝牙
    } else {
      flutterBlue.stopScan();
    }
    return Future.value(true);
    // _showDialog();
    //  return Future.value(false);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    print('生命周期变化');
    print(state);
    // if (state == AppLifecycleState.paused) {
    //   setState(() {
    //     canceltimes = true;
    //   });
    // } else if (state == AppLifecycleState.resumed) {
    //   setState(() {
    //     canceltimes = false;
    //   });
    // }
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('此项是否已经检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(this.context).pop();
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}

class SignaturePainter extends CustomPainter {
  SignaturePainter(this.points);

  final List<Offset> points; // Offset:一个不可变的2D浮点偏移。

  void paint(Canvas canvas, Size size) {
    Paint paint = new Paint() //设置笔的属性
      ..color = Colors.red[800]
      ..strokeCap = StrokeCap.round
      ..isAntiAlias = true
      ..strokeWidth = 2.0
      ..strokeJoin = StrokeJoin.bevel;

    for (int i = 0; i < points.length - 1; i++) {
      //画线
      if (points[i] != null && points[i + 1] != null)
        canvas.drawLine(points[i], points[i + 1],
            paint); //drawLine(Offset p1, Offset p2, Paint paint) → void
//      canvas.drawOval(
//          new Rect.fromCircle(center: points[i], radius: 20.0), paint);
////      canvas.drawOval(rect, paint)
//    canvas.drawCircle(points[i], 20.0, paint);
    }
  }

  /**
   * 是否重绘
   */
  bool shouldRepaint(SignaturePainter other) => other.points != points;
//  bool shouldRepaint(SignaturePainter other) =>true;
}
